Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

refactor: replace dict-style access with dot access on Block/Line/Span canonical fields

jinzhenje049a08d4571
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 570402ce..8d236144 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -374,7 +374,7 @@ def _has_doc_title_overlap(title_bbox: list[float], doc_title_bboxes: list[list[
def _apply_layout_title_split(
model_list: list[list[dict[str, object]]],
images_layout_res: list[list[dict[str, object]]],
- page_sizes: list[tuple[int, int]],
+ page_sizes: list[list[int]],
overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,
) -> None:
"""用layout doc_title框将VLM title拆分为doc_title和paragraph_title。"""
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index 463b0680..3ed4a095 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -31,7 +31,6 @@ not_extract_list = [item.value for item in NotExtractType] + [
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
]
-OCR_DET_LINES_KEY = "_ocr_det_lines"
OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {
BlockType.LIST,
BlockType.INDEX,
@@ -48,7 +47,7 @@ def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, obj
if raw_block_type != BlockType.TEXT:
return
if "merge_prev" in block_info:
- block["merge_prev"] = block_info["merge_prev"]
+ block.merge_prev = block_info["merge_prev"]
class MagicModel:
@@ -278,17 +277,16 @@ class MagicModel:
else:
line = Line(spans=spans, bbox=block_bbox)
- block = Block(type=block_type, bbox=block_bbox, lines=[line])
- block["angle"] = block_angle
- block["index"] = index
+ block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)
+ block.index = index
if block_sub_type:
- block["sub_type"] = block_sub_type
+ block.sub_type = block_sub_type
if raw_block_type == "table" and "cell_merge" in block_info:
block["cell_merge"] = block_info["cell_merge"]
if _vlm_ocr_enable and self._supports_ocr_det_lines(block_type):
ocr_det_lines = self._build_ocr_det_lines(span_matcher.collect_for_block(block_bbox))
if ocr_det_lines:
- block[OCR_DET_LINES_KEY] = ocr_det_lines
+ block._ocr_det_lines = ocr_det_lines
_copy_raw_text_block_metadata(raw_block_type, block_info, block)
else:
block_spans = span_matcher.collect_for_block(block_bbox)
@@ -321,11 +319,11 @@ class MagicModel:
self.list_blocks = []
for block in blocks:
- if block["type"] in VISUAL_MAIN_TYPES or block["type"] in GENERIC_CHILD_TYPES:
+ if block.type in VISUAL_MAIN_TYPES or block.type in GENERIC_CHILD_TYPES:
continue
- elif block["type"] == BlockType.INTERLINE_EQUATION:
+ elif block.type == BlockType.INTERLINE_EQUATION:
self.interline_equation_blocks.append(block)
- elif block["type"] == BlockType.TEXT:
+ elif block.type == BlockType.TEXT:
self.text_blocks.append(block)
elif block["type"] in [
BlockType.TITLE,
@@ -333,11 +331,11 @@ class MagicModel:
BlockType.PARAGRAPH_TITLE,
]:
self.title_blocks.append(block)
- elif block["type"] == BlockType.REF_TEXT:
+ elif block.type == BlockType.REF_TEXT:
self.ref_text_blocks.append(block)
- elif block["type"] == BlockType.PHONETIC:
+ elif block.type == BlockType.PHONETIC:
self.phonetic_blocks.append(block)
- elif block["type"] in [
+ elif block.type in [
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
@@ -345,7 +343,7 @@ class MagicModel:
BlockType.PAGE_FOOTNOTE,
]:
self.discarded_blocks.append(block)
- elif block["type"] == BlockType.LIST:
+ elif block.type == BlockType.LIST:
self.list_blocks.append(block)
self.list_blocks, self.text_blocks, self.ref_text_blocks = fix_list_blocks(
@@ -361,20 +359,20 @@ class MagicModel:
self.code_blocks = visual_groups[BlockType.CODE]
for code_block in self.code_blocks:
- for block in code_block["blocks"]:
- if block["type"] == BlockType.CODE_BODY:
- if block["lines"]:
- line = block["lines"][0]
- code_block["sub_type"] = line["extra"]["type"]
- if code_block["sub_type"] == "code":
- code_block["guess_lang"] = line["extra"]["guess_lang"]
+ for block in code_block.blocks:
+ if block.type == BlockType.CODE_BODY:
+ if block.lines:
+ line = block.lines[0]
+ code_block.sub_type = line["extra"]["type"]
+ if code_block.sub_type == "code":
+ code_block.guess_lang = line["extra"]["guess_lang"]
del line["extra"]
else:
- code_block["sub_type"] = "code"
- code_block["guess_lang"] = "txt"
+ code_block.sub_type = "code"
+ code_block.guess_lang = "txt"
for block in unmatched_child_blocks:
- block["type"] = BlockType.TEXT
+ block.type = BlockType.TEXT
self.text_blocks.append(block)
@staticmethod
@@ -408,7 +406,7 @@ class MagicModel:
return []
hint_block = {"spans": copy.deepcopy(block_spans)}
- return fix_text_block(hint_block).get("lines", [])
+ return fix_text_block(hint_block)["lines"]
def cal_real_bbox(self, bbox: list[float]) -> tuple[int, int, int, int]:
x1, y1, x2, y2 = bbox
@@ -465,9 +463,9 @@ def fix_list_blocks(
list_blocks: list[Block], text_blocks: list[Block], ref_text_blocks: list[Block]
) -> tuple[list[Block], list[Block], list[Block]]:
for list_block in list_blocks:
- list_block["blocks"] = []
- if "lines" in list_block:
- del list_block["lines"]
+ list_block.blocks = []
+ if list_block.lines:
+ list_block.lines = []
temp_text_blocks = text_blocks + ref_text_blocks
need_remove_blocks = []
@@ -475,12 +473,12 @@ def fix_list_blocks(
for list_block in list_blocks:
if (
calculate_overlap_area_in_bbox1_area_ratio(
- block["bbox"],
- list_block["bbox"],
+ block.bbox,
+ list_block.bbox,
)
>= 0.8
):
- list_block["blocks"].append(block)
+ list_block.blocks.append(block)
need_remove_blocks.append(block)
break
@@ -490,19 +488,19 @@ def fix_list_blocks(
elif block in ref_text_blocks:
ref_text_blocks.remove(block)
- list_blocks = [lb for lb in list_blocks if lb["blocks"]]
+ list_blocks = [lb for lb in list_blocks if lb.blocks]
for list_block in list_blocks:
type_count = {}
- for sub_block in list_block["blocks"]:
- sub_block_type = sub_block["type"]
+ for sub_block in list_block.blocks:
+ sub_block_type = sub_block.type
if sub_block_type not in type_count:
type_count[sub_block_type] = 0
type_count[sub_block_type] += 1
if type_count:
- list_block["sub_type"] = max(type_count, key=type_count.get)
+ list_block.sub_type = max(type_count, key=type_count.get)
else:
- list_block["sub_type"] = "unknown"
+ list_block.sub_type = "unknown"
return list_blocks, text_blocks, ref_text_blocks
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index 199ea205..fd199130 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -18,7 +18,6 @@ from ..pipeline.model_init import MineruHybridModel
from ..utils.html_image_utils import replace_inline_table_images
from ..utils.middle_json_utils import apply_post_ocr, build_middle_json
from ..utils.para_block_utils import (
- OCR_DET_LINES_KEY,
build_para_blocks_from_preproc,
cleanup_internal_para_block_metadata,
merge_para_text_blocks,
@@ -29,10 +28,10 @@ from .hybrid_magic_model import MagicModel
def _resolve_title_line_avg_height(title_block: Block) -> int:
"""解析标题平均行高:优先复用 Hybrid OCR det 行提示,再回退到原始行或块高。"""
- for lines_key in [OCR_DET_LINES_KEY, "lines"]:
+ for lines in [title_block._ocr_det_lines, title_block.lines]:
line_heights = []
- for line in title_block.get(lines_key, []):
- bbox = line.get("bbox")
+ for line in lines:
+ bbox = line.bbox
if not bbox or len(bbox) < 4:
continue
line_height = bbox[3] - bbox[1]
@@ -40,11 +39,7 @@ def _resolve_title_line_avg_height(title_block: Block) -> int:
line_heights.append(line_height)
if line_heights:
return round(sum(line_heights) / len(line_heights))
-
- bbox = title_block.get("bbox", [0, 0, 0, 0])
- if len(bbox) >= 4:
- return bbox[3] - bbox[1]
- return 0
+ return int(title_block.bbox[3] - title_block.bbox[1])
def blocks_to_page_info(
@@ -86,7 +81,7 @@ def blocks_to_page_info(
# 标题平均行高是 finalized middle json 的稳定字段,供服务端和客户端标题分级共用。
for title_block in title_blocks:
- title_block["line_avg_height"] = _resolve_title_line_avg_height(title_block)
+ title_block._line_avg_height = _resolve_title_line_avg_height(title_block)
text_blocks = magic_model.get_text_blocks()
interline_equation_blocks = magic_model.get_interline_equation_blocks()
@@ -94,7 +89,7 @@ def blocks_to_page_info(
all_spans = magic_model.get_all_spans()
# 对image/table/chart/interline_equation的span截图
for span in all_spans:
- if span["type"] in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART, ContentType.INTERLINE_EQUATION]:
+ if span.type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART, ContentType.INTERLINE_EQUATION]:
span = cut_image_and_table(span, page_pil_img, page_img_md5, page_index, image_writer, scale=scale)
replace_inline_table_images(table_blocks, image_writer, page_index)
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 690f0481..d0c1ad27 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -6,7 +6,7 @@ import re
from typing import Any, Literal
from urllib.parse import urlparse
-from ...types import Block, Line, Span
+from ...types import EMPTY_BBOX, Block, Line, Span
from ...utils.enum_class import BlockType, ContentType
from ...utils.magic_model_utils import tie_up_category_by_index
@@ -15,7 +15,7 @@ class MagicModel:
def __init__(self, page_blocks: list[dict[str, Any]]) -> None:
self.page_blocks = page_blocks
- blocks = []
+ blocks: list[Block] = []
self.all_spans = []
# 对caption块进行分类,将其分类为image_caption, table_caption, chart_caption
@@ -42,31 +42,31 @@ class MagicModel:
elif block_type in ["image"]:
block_type = BlockType.IMAGE_BODY
- span = Span(type=ContentType.IMAGE, image_base64=block_content)
+ span = Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_base64=block_content)
elif block_type in ["table"]:
block_type = BlockType.TABLE_BODY
- span = Span(type=ContentType.TABLE, html=clean_table_html(block_content))
+ span = Span(type=ContentType.TABLE, bbox=EMPTY_BBOX, html=clean_table_html(block_content))
elif block_type in ["chart"]:
block_type = BlockType.CHART_BODY
- span = Span(type=ContentType.CHART, content=block_content)
+ span = Span(type=ContentType.CHART, bbox=EMPTY_BBOX, content=block_content)
if block_info.get("image_base64"):
- span["image_base64"] = block_info["image_base64"]
+ span.image_base64 = block_info["image_base64"]
elif block_type in ["equation"]:
block_type = BlockType.INTERLINE_EQUATION
- span = Span(type=ContentType.INTERLINE_EQUATION, content=block_content)
+ span = Span(type=ContentType.INTERLINE_EQUATION, bbox=EMPTY_BBOX, content=block_content)
elif block_type in ["list"]:
# 解析嵌套列表结构,生成与VLM一致的blocks结构
parsed_list = parse_list_block(block_info)
if parsed_list:
# 使用外层index作为列表block的index
- parsed_list["index"] = index
+ parsed_list.index = index
blocks.append(parsed_list)
continue
elif block_type in ["index"]:
# 解析嵌套索引结构(目录),生成与list一致的blocks结构
parsed_index = parse_index_block(block_info)
if parsed_index:
- parsed_index["index"] = index
+ parsed_index.index = index
blocks.append(parsed_index)
continue
else:
@@ -75,17 +75,13 @@ class MagicModel:
# 处理span类型并添加到all_spans
if isinstance(span, Span):
- line = Line(spans=[span])
+ line = Line(bbox=EMPTY_BBOX, spans=[span])
elif isinstance(span, list):
- line = Line(spans=span)
+ line = Line(bbox=EMPTY_BBOX, spans=span)
else:
raise ValueError(f"Unsupported span type: {type(span)}")
- block = Block(
- type=block_type,
- lines=[line],
- )
- block["index"] = index
+ block = Block(type=block_type, bbox=EMPTY_BBOX, lines=[line], index=index)
anchor = block_info.get("anchor")
if (
isinstance(anchor, str)
@@ -95,36 +91,36 @@ class MagicModel:
block["anchor"] = anchor.strip()
if block_type == BlockType.TITLE:
block["is_numbered_style"] = block_info.get("is_numbered_style", False)
- block["level"] = block_info.get("level", 1)
+ block.level = block_info.get("level", 1)
blocks.append(block)
- self.image_blocks = []
- self.table_blocks = []
- self.chart_blocks = []
- self.interline_equation_blocks = []
- self.text_blocks = []
- self.title_blocks = []
- self.discarded_blocks = []
- self.list_blocks = []
- self.index_blocks = []
+ self.image_blocks: list[Block] = []
+ self.table_blocks: list[Block] = []
+ self.chart_blocks: list[Block] = []
+ self.interline_equation_blocks: list[Block] = []
+ self.text_blocks: list[Block] = []
+ self.title_blocks: list[Block] = []
+ self.discarded_blocks: list[Block] = []
+ self.list_blocks: list[Block] = []
+ self.index_blocks: list[Block] = []
for block in blocks:
- if block["type"] in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:
+ if block.type in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:
self.image_blocks.append(block)
- elif block["type"] in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:
+ elif block.type in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:
self.table_blocks.append(block)
- elif block["type"] in [BlockType.CHART_BODY, BlockType.CHART_CAPTION]:
+ elif block.type in [BlockType.CHART_BODY, BlockType.CHART_CAPTION]:
self.chart_blocks.append(block)
- elif block["type"] == BlockType.INTERLINE_EQUATION:
+ elif block.type == BlockType.INTERLINE_EQUATION:
self.interline_equation_blocks.append(block)
- elif block["type"] == BlockType.TEXT:
+ elif block.type == BlockType.TEXT:
self.text_blocks.append(block)
- elif block["type"] == BlockType.TITLE:
+ elif block.type == BlockType.TITLE:
self.title_blocks.append(block)
- elif block["type"] in [BlockType.REF_TEXT]:
+ elif block.type in [BlockType.REF_TEXT]:
self.ref_text_blocks.append(block)
- elif block["type"] in [BlockType.PHONETIC]:
+ elif block.type in [BlockType.PHONETIC]:
self.phonetic_blocks.append(block)
- elif block["type"] in [
+ elif block.type in [
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
@@ -132,9 +128,9 @@ class MagicModel:
BlockType.PAGE_FOOTNOTE,
]:
self.discarded_blocks.append(block)
- elif block["type"] == BlockType.LIST:
+ elif block.type == BlockType.LIST:
self.list_blocks.append(block)
- elif block["type"] == BlockType.INDEX:
+ elif block.type == BlockType.INDEX:
self.index_blocks.append(block)
else:
continue
@@ -263,7 +259,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
if not candidates:
remaining_text = content[last_end:]
if remaining_text:
- spans.append(Span(type=ContentType.TEXT, content=remaining_text))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=remaining_text))
break
# 取位置最小的标签
@@ -273,19 +269,19 @@ def parse_text_block_spans(content: str) -> list[Span]:
if next_tag_pos > last_end:
text_before = content[last_end:next_tag_pos]
if text_before:
- spans.append(Span(type=ContentType.TEXT, content=text_before))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=text_before))
# 处理行内公式
if next_tag_type == "eq":
eq_end = content.find("</eq>", next_tag_pos)
if eq_end != -1:
formula_content = content[next_tag_pos + 4 : eq_end]
- spans.append(Span(type=ContentType.INLINE_EQUATION, content=formula_content))
+ spans.append(Span(type=ContentType.INLINE_EQUATION, bbox=EMPTY_BBOX, content=formula_content))
pos = eq_end + 5
last_end = pos
else:
# 未找到闭合标签,将<eq>作为普通文本处理
- spans.append(Span(type=ContentType.TEXT, content=content[last_end:]))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=content[last_end:]))
break
# 处理带样式的文本标签
@@ -297,7 +293,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
tag_open_end = content.find(">", next_tag_pos) + 1
text_content = content[tag_open_end:text_end]
style_str = text_tag_match.group(1) if text_tag_match and text_tag_match.start() == next_tag_pos else None
- span = Span(type=ContentType.TEXT, content=text_content)
+ span = Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=text_content)
if style_str:
span["style"] = [s.strip() for s in style_str.split(",") if s.strip()]
spans.append(span)
@@ -305,7 +301,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
last_end = pos
else:
# 未找到闭合标签,作为普通文本处理
- spans.append(Span(type=ContentType.TEXT, content=content[last_end:]))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=content[last_end:]))
break
# 处理超链接
@@ -326,6 +322,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
child = children[0]
span = Span(
type=ContentType.HYPERLINK,
+ bbox=EMPTY_BBOX,
content=child["content"],
)
span["url"] = link_url
@@ -334,6 +331,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
else:
span = Span(
type=ContentType.HYPERLINK,
+ bbox=EMPTY_BBOX,
content="".join(child["content"] for child in children),
)
span["url"] = link_url
@@ -343,11 +341,11 @@ def parse_text_block_spans(content: str) -> list[Span]:
last_end = pos
else:
# 超链接格式不正确,作为普通文本处理
- spans.append(Span(type=ContentType.TEXT, content=content[last_end:]))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=content[last_end:]))
break
else:
# 未找到闭合标签,将<hyperlink>作为普通文本处理
- spans.append(Span(type=ContentType.TEXT, content=content[last_end:]))
+ spans.append(Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content=content[last_end:]))
break
return spans
@@ -376,7 +374,7 @@ def parse_list_block(list_block: dict[str, object]) -> Block:
# 解析文本项(可能包含行内公式和超链接)
text_content = item.get("content", "")
spans = parse_text_block_spans(text_content)
- text_block = Block(type=BlockType.TEXT, lines=[Line(spans=spans)])
+ text_block = Block(type=BlockType.TEXT, bbox=EMPTY_BBOX, index=0, lines=[Line(bbox=EMPTY_BBOX, spans=spans)])
blocks.append(text_block)
elif item_type == "list":
@@ -386,7 +384,7 @@ def parse_list_block(list_block: dict[str, object]) -> Block:
blocks.append(nested_list)
# 构建当前列表block
- result = Block(type=BlockType.LIST, blocks=blocks)
+ result = Block(type=BlockType.LIST, bbox=EMPTY_BBOX, index=0, blocks=blocks)
result["attribute"] = list_block.get("attribute", "unordered")
result["ilevel"] = list_block.get("ilevel", 0)
if "start" in list_block:
@@ -417,7 +415,7 @@ def parse_index_block(index_block: dict[str, object]) -> Block:
if item_type == "text":
text_content = item.get("content", "")
spans = parse_text_block_spans(text_content)
- text_block = Block(type=BlockType.TEXT, lines=[Line(spans=spans)])
+ text_block = Block(type=BlockType.TEXT, bbox=EMPTY_BBOX, index=0, lines=[Line(bbox=EMPTY_BBOX, spans=spans)])
anchor = item.get("anchor")
if isinstance(anchor, str) and anchor.strip():
text_block["anchor"] = anchor.strip()
@@ -428,7 +426,7 @@ def parse_index_block(index_block: dict[str, object]) -> Block:
if nested_index:
blocks.append(nested_index)
- result = Block(type=BlockType.INDEX, blocks=blocks)
+ result = Block(type=BlockType.INDEX, bbox=EMPTY_BBOX, index=0, blocks=blocks)
result["ilevel"] = index_block.get("ilevel", 0)
return result
@@ -578,26 +576,22 @@ def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, obj
# 定义获取主体和客体对象的函数
def get_subjects() -> list[dict[str, object]]:
- return list(
- map(
- lambda x: {"lines": x["lines"], "index": x["index"]},
- filter(
- lambda x: x["type"] == subject_block_type,
- blocks,
- ),
+ return [
+ {"lines": block.lines, "index": block.index}
+ for block in filter(
+ lambda b: b.type == subject_block_type,
+ blocks,
)
- )
+ ]
def get_objects() -> list[dict[str, object]]:
- return list(
- map(
- lambda x: {"lines": x["lines"], "index": x["index"]},
- filter(
- lambda x: x["type"] == object_block_type,
- blocks,
- ),
+ return [
+ {"lines": block.lines, "index": block.index}
+ for block in filter(
+ lambda b: b.type == object_block_type,
+ blocks,
)
- )
+ ]
# 调用通用方法
return tie_up_category_by_index(
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
index a9f71959..f74bee3c 100644
--- a/mineru/backend/pipeline/batch_analyze.py
+++ b/mineru/backend/pipeline/batch_analyze.py
@@ -4,40 +4,41 @@ from __future__ import annotations
import base64
import html
import re
+from collections import defaultdict
from typing import Any
import cv2
import numpy as np
-from PIL import Image
from loguru import logger
+from PIL import Image
from tqdm import tqdm
-from collections import defaultdict
-import numpy as np
-from .model_init import (
- AtomModelSingleton,
- run_layout_inference,
- run_mfr_inference,
- run_ocr_det_inference,
- run_ocr_rec_inference,
-)
-from .pipeline_analyze import ModelSingleton
-from .model_list import AtomicModel
+from ...utils.bbox_utils import normalize_to_int_bbox
from ...utils.config_reader import (
get_formula_enable,
get_ocr_det_mask_inline_formula_enable,
get_table_enable,
)
-from ...utils.bbox_utils import normalize_to_int_bbox
-from ...utils.model_utils import crop_img, get_res_list_from_layout_res, clean_vram
-from ...utils.ocr_utils import merge_det_boxes, update_det_boxes, sorted_boxes
+from ...utils.model_utils import clean_vram, crop_img, get_res_list_from_layout_res
from ...utils.ocr_utils import (
+ OcrConfidence,
get_adjusted_mfdetrec_res,
get_ocr_result_list,
- OcrConfidence,
get_rotate_crop_image_for_text_rec,
+ merge_det_boxes,
+ sorted_boxes,
+ update_det_boxes,
)
from ...utils.pdf_image_tools import get_crop_np_img
+from .model_init import (
+ AtomModelSingleton,
+ run_layout_inference,
+ run_mfr_inference,
+ run_ocr_det_inference,
+ run_ocr_rec_inference,
+)
+from .model_list import AtomicModel
+from .pipeline_analyze import ModelSingleton
LAYOUT_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16
@@ -76,9 +77,7 @@ class BatchAnalyze:
self.text_ocr_det_batch_enabled = (
enable_ocr_det_batch if text_ocr_det_batch_enabled is None else text_ocr_det_batch_enabled
)
- self.mask_inline_formula_for_ocr_det = (
- get_ocr_det_mask_inline_formula_enable(mask_inline_formula_for_ocr_det)
- )
+ self.mask_inline_formula_for_ocr_det = get_ocr_det_mask_inline_formula_enable(mask_inline_formula_for_ocr_det)
@staticmethod
def _apply_mask_boxes_to_image(
@@ -243,10 +242,7 @@ class BatchAnalyze:
for j in range(i, -1, -1):
cur_box = np.asarray(sorted_result[j][0], dtype=np.float32)
next_box = np.asarray(sorted_result[j + 1][0], dtype=np.float32)
- if (
- abs(float(next_box[0][1]) - float(cur_box[0][1])) < 10
- and float(next_box[0][0]) < float(cur_box[0][0])
- ):
+ if abs(float(next_box[0][1]) - float(cur_box[0][1])) < 10 and float(next_box[0][0]) < float(cur_box[0][0]):
sorted_result[j], sorted_result[j + 1] = sorted_result[j + 1], sorted_result[j]
else:
break
@@ -355,7 +351,6 @@ class BatchAnalyze:
return table_inline_objects
-
def __call__(self, images_with_extra_info: list[tuple[Image.Image, bool, str]]) -> list[list[dict[str, Any]]]:
if len(images_with_extra_info) == 0:
return []
@@ -402,9 +397,7 @@ class BatchAnalyze:
mfr_count = 0
for image_index in range(len(np_images)):
mfr_count += len(images_formula_list[image_index])
- for formula_res, formula_with_latex in zip(
- images_mfd_res[image_index], images_formula_list[image_index]
- ):
+ for formula_res, formula_with_latex in zip(images_mfd_res[image_index], images_formula_list[image_index]):
formula_res["latex"] = formula_with_latex.get("latex", "")
# 清理显存
@@ -415,8 +408,6 @@ class BatchAnalyze:
# 移除所有的"inline_formula"
layout_res[:] = [res for res in layout_res if res.get("label") != "inline_formula"]
-
-
ocr_res_list_all_page = []
table_res_list_all_page = []
for index in range(len(np_images)):
@@ -433,45 +424,47 @@ class BatchAnalyze:
else {}
)
- ocr_res_list, table_res_list, single_page_mfdetrec_res = (
- get_res_list_from_layout_res(layout_res)
- )
+ ocr_res_list, table_res_list, single_page_mfdetrec_res = get_res_list_from_layout_res(layout_res)
- ocr_res_list_all_page.append({'ocr_res_list':ocr_res_list,
- 'lang':_lang,
- 'ocr_enable':ocr_enable,
- 'np_img':np_img,
- 'single_page_mfdetrec_res':single_page_mfdetrec_res,
- 'layout_res':layout_res,
- })
+ ocr_res_list_all_page.append(
+ {
+ "ocr_res_list": ocr_res_list,
+ "lang": _lang,
+ "ocr_enable": ocr_enable,
+ "np_img": np_img,
+ "single_page_mfdetrec_res": single_page_mfdetrec_res,
+ "layout_res": layout_res,
+ }
+ )
for table_res in table_res_list:
- def get_crop_table_img(scale: float) -> Image.Image:
- bbox = normalize_to_int_bbox(
- [float(v) / float(scale) for v in table_res["bbox"]]
- )
+
+ def get_crop_table_img(scale: float) -> np.ndarray:
+ bbox = normalize_to_int_bbox([float(v) / float(scale) for v in table_res["bbox"]])
if bbox is None:
return np_img[0:0, 0:0]
return get_crop_np_img(bbox, np_img, scale=scale)
- wireless_table_img = get_crop_table_img(scale = 1)
- wired_table_img = get_crop_table_img(scale = 10/3)
+ wireless_table_img = get_crop_table_img(scale=1)
+ wired_table_img = get_crop_table_img(scale=10 / 3)
table_page_bbox = normalize_to_int_bbox(
table_res.get("bbox"),
image_size=np_img.shape[:2],
) or [0, 0, 0, 0]
- table_res_list_all_page.append({'table_res':table_res,
- 'lang':_lang,
- 'table_img':wireless_table_img,
- 'wired_table_img':wired_table_img,
- 'table_page_bbox':table_page_bbox,
- 'table_inline_objects':table_inline_objects.get(id(table_res), []),
- })
+ table_res_list_all_page.append(
+ {
+ "table_res": table_res,
+ "lang": _lang,
+ "table_img": wireless_table_img,
+ "wired_table_img": wired_table_img,
+ "table_page_bbox": table_page_bbox,
+ "table_inline_objects": table_inline_objects.get(id(table_res), []),
+ }
+ )
# 表格识别 table recognition
if self.table_enable:
-
# 图片旋转批量处理
table_orientation_cls_model = atom_model_manager.get_atom_model(
atom_model_name=AtomicModel.TableOrientationCls,
@@ -483,31 +476,24 @@ class BatchAnalyze:
det_batch_size=self.batch_ratio * OCR_DET_BASE_BATCH_SIZE,
)
if len(rotate_labels) != len(table_res_list_all_page):
- raise ValueError(
- "Table orientation batch prediction result count mismatch"
- )
+ raise ValueError("Table orientation batch prediction result count mismatch")
for table_res, rotate_label in zip(table_res_list_all_page, rotate_labels):
self._apply_table_rotate_label(table_res, rotate_label)
else:
for table_res in table_res_list_all_page:
- rotate_label = table_orientation_cls_model.predict(table_res['table_img'])
+ rotate_label = table_orientation_cls_model.predict(table_res["table_img"])
self._apply_table_rotate_label(table_res, rotate_label)
except Exception as e:
- logger.warning(
- f"Table orientation classification failed: {e}, using original image"
- )
+ logger.warning(f"Table orientation classification failed: {e}, using original image")
# 表格分类
table_cls_model = atom_model_manager.get_atom_model(
atom_model_name=AtomicModel.TableCls,
)
try:
- table_cls_model.batch_predict(table_res_list_all_page,
- batch_size=TABLE_Wired_Wireless_CLS_BATCH_SIZE)
+ table_cls_model.batch_predict(table_res_list_all_page, batch_size=TABLE_Wired_Wireless_CLS_BATCH_SIZE)
except Exception as e:
- logger.warning(
- f"Table classification failed: {e}, using default model"
- )
+ logger.warning(f"Table classification failed: {e}, using default model")
# OCR det 过程,顺序执行
rec_img_lang_group = defaultdict(list)
@@ -517,32 +503,21 @@ class BatchAnalyze:
det_db_unclip_ratio=1.6,
enable_merge_det_boxes=False,
)
- for index, table_res_dict in enumerate(
- tqdm(table_res_list_all_page, desc="Table-ocr det")
- ):
+ for index, table_res_dict in enumerate(tqdm(table_res_list_all_page, desc="Table-ocr det")):
bgr_image = cv2.cvtColor(table_res_dict["table_img"], cv2.COLOR_RGB2BGR)
table_inline_objects = (
table_res_dict.get("table_inline_objects", [])
if self._table_supports_inline_objects(table_res_dict)
else []
)
- inline_mask_boxes = [
- {"bbox": inline_object["table_rel_mask_bbox"]}
- for inline_object in table_inline_objects
- ]
+ inline_mask_boxes = [{"bbox": inline_object["table_rel_mask_bbox"]} for inline_object in table_inline_objects]
formula_mask_boxes = [
{"bbox": inline_object["table_rel_mask_bbox"]}
for inline_object in table_inline_objects
if inline_object["kind"] == "formula"
]
- det_image = (
- self._apply_mask_boxes_to_image(bgr_image, inline_mask_boxes)
- if inline_mask_boxes
- else bgr_image
- )
- ocr_result = run_ocr_det_inference(
- det_ocr_engine.ocr, det_image, rec=False
- )[0]
+ det_image = self._apply_mask_boxes_to_image(bgr_image, inline_mask_boxes) if inline_mask_boxes else bgr_image
+ ocr_result = run_ocr_det_inference(det_ocr_engine.ocr, det_image, rec=False)[0]
if ocr_result and formula_mask_boxes:
ocr_result = update_det_boxes(ocr_result, formula_mask_boxes)
if ocr_result:
@@ -551,9 +526,7 @@ class BatchAnalyze:
for dt_box in ocr_result:
rec_img_lang_group[table_res_dict["lang"]].append(
{
- "cropped_img": get_rotate_crop_image_for_text_rec(
- bgr_image, np.asarray(dt_box, dtype=np.float32)
- ),
+ "cropped_img": get_rotate_crop_image_for_text_rec(bgr_image, np.asarray(dt_box, dtype=np.float32)),
"dt_box": np.asarray(dt_box, dtype=np.float32),
"table_id": index,
}
@@ -583,13 +556,9 @@ class BatchAnalyze:
ocr_text = self._normalize_table_ocr_rec_text(ocr_res[0])
ocr_result_item = [img_dict["dt_box"], html.escape(ocr_text), ocr_res[1]]
if table_res_list_all_page[img_dict["table_id"]].get("ocr_result"):
- table_res_list_all_page[img_dict["table_id"]]["ocr_result"].append(
- ocr_result_item
- )
+ table_res_list_all_page[img_dict["table_id"]]["ocr_result"].append(ocr_result_item)
else:
- table_res_list_all_page[img_dict["table_id"]]["ocr_result"] = [
- ocr_result_item
- ]
+ table_res_list_all_page[img_dict["table_id"]]["ocr_result"] = [ocr_result_item]
# 先对所有表格使用无线表格模型,然后对分类为有线的表格使用有线表格模型
for table_res_dict in table_res_list_all_page:
@@ -622,16 +591,14 @@ class BatchAnalyze:
for table_res_dict in table_res_list_all_page:
# logger.debug(f"Table classification result: {table_res_dict["table_res"]["cls_label"]} with confidence {table_res_dict["table_res"]["cls_score"]}")
if (
- (table_res_dict["table_res"]["cls_label"] == AtomicModel.WirelessTable and table_res_dict["table_res"]["cls_score"] < 0.9)
- or table_res_dict["table_res"]["cls_label"] == AtomicModel.WiredTable
- ):
+ table_res_dict["table_res"]["cls_label"] == AtomicModel.WirelessTable
+ and table_res_dict["table_res"]["cls_score"] < 0.9
+ ) or table_res_dict["table_res"]["cls_label"] == AtomicModel.WiredTable:
wired_table_res_list.append(table_res_dict)
del table_res_dict["table_res"]["cls_label"]
del table_res_dict["table_res"]["cls_score"]
if wired_table_res_list:
- for table_res_dict in tqdm(
- wired_table_res_list, desc="Table-wired Predict"
- ):
+ for table_res_dict in tqdm(wired_table_res_list, desc="Table-wired Predict"):
if not table_res_dict.get("ocr_result", None):
continue
@@ -642,7 +609,7 @@ class BatchAnalyze:
table_res_dict["table_res"]["html"] = wired_table_model.predict(
table_res_dict["wired_table_img"],
table_res_dict["ocr_result"],
- table_res_dict["table_res"].get("html", None)
+ table_res_dict["table_res"].get("html", None),
)
# 表格格式清理
@@ -656,7 +623,6 @@ class BatchAnalyze:
end_index = html_code.rfind("</table>") + len("</table>")
table_res_dict["table_res"]["html"] = html_code[start_index:end_index]
-
# OCR det
if self.text_ocr_det_batch_enabled:
# 批处理模式 - 按语言和分辨率分组
@@ -664,14 +630,12 @@ class BatchAnalyze:
all_cropped_images_info = []
for ocr_res_list_dict in ocr_res_list_all_page:
- _lang = ocr_res_list_dict['lang']
+ _lang = ocr_res_list_dict["lang"]
- for res in ocr_res_list_dict['ocr_res_list']:
- new_image, useful_list = crop_img(
- res, ocr_res_list_dict['np_img'], crop_paste_x=50, crop_paste_y=50
- )
+ for res in ocr_res_list_dict["ocr_res_list"]:
+ new_image, useful_list = crop_img(res, ocr_res_list_dict["np_img"], crop_paste_x=50, crop_paste_y=50)
adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
- ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
+ ocr_res_list_dict["single_page_mfdetrec_res"], useful_list
)
# BGR转换
@@ -681,14 +645,16 @@ class BatchAnalyze:
adjusted_mfdetrec_res,
)
- all_cropped_images_info.append((
- bgr_image,
- det_image,
- useful_list,
- ocr_res_list_dict,
- adjusted_mfdetrec_res,
- _lang,
- ))
+ all_cropped_images_info.append(
+ (
+ bgr_image,
+ det_image,
+ useful_list,
+ ocr_res_list_dict,
+ adjusted_mfdetrec_res,
+ _lang,
+ )
+ )
# 按语言分组
lang_groups = defaultdict(list)
@@ -704,10 +670,7 @@ class BatchAnalyze:
# logger.info(f"Processing OCR detection for language {lang} with {len(lang_crop_list)} images")
# 获取OCR模型
- ocr_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang=lang
- )
+ ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=lang)
# 按分辨率分组并同时完成padding
# RESOLUTION_GROUP_STRIDE = 32
@@ -737,9 +700,7 @@ class BatchAnalyze:
# 批处理检测
det_batch_size = min(len(batch_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE)
- batch_results = run_ocr_det_inference(
- ocr_model.text_detector.batch_predict, batch_images, det_batch_size
- )
+ batch_results = run_ocr_det_inference(ocr_model.text_detector.batch_predict, batch_images, det_batch_size)
# 处理批处理结果
for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):
@@ -758,20 +719,22 @@ class BatchAnalyze:
dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []
# 根据公式位置更新检测框
- dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)
- if dt_boxes_merged and adjusted_mfdetrec_res
- else dt_boxes_merged)
+ dt_boxes_final = (
+ update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)
+ if dt_boxes_merged and adjusted_mfdetrec_res
+ else dt_boxes_merged
+ )
if dt_boxes_final:
- ocr_res = [box.tolist() if hasattr(box, 'tolist') else box for box in dt_boxes_final]
+ ocr_res = [box.tolist() if hasattr(box, "tolist") else box for box in dt_boxes_final]
ocr_result_list = get_ocr_result_list(
ocr_res,
useful_list,
- ocr_res_list_dict['ocr_enable'],
+ ocr_res_list_dict["ocr_enable"],
bgr_image,
_lang,
)
- ocr_res_list_dict['layout_res'].extend(ocr_result_list)
+ ocr_res_list_dict["layout_res"].extend(ocr_result_list)
# 清理显存
clean_vram(self.model.device, vram_threshold=8)
@@ -780,18 +743,13 @@ class BatchAnalyze:
# 原始单张处理模式
for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
# Process each area that requires OCR processing
- _lang = ocr_res_list_dict['lang']
+ _lang = ocr_res_list_dict["lang"]
# Get OCR results for this language's images
- ocr_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang=_lang
- )
- for res in ocr_res_list_dict['ocr_res_list']:
- new_image, useful_list = crop_img(
- res, ocr_res_list_dict['np_img'], crop_paste_x=50, crop_paste_y=50
- )
+ ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=_lang)
+ for res in ocr_res_list_dict["ocr_res_list"]:
+ new_image, useful_list = crop_img(res, ocr_res_list_dict["np_img"], crop_paste_x=50, crop_paste_y=50)
adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
- ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
+ ocr_res_list_dict["single_page_mfdetrec_res"], useful_list
)
# OCR-det
bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
@@ -811,12 +769,12 @@ class BatchAnalyze:
ocr_result_list = get_ocr_result_list(
ocr_res,
useful_list,
- ocr_res_list_dict['ocr_enable'],
+ ocr_res_list_dict["ocr_enable"],
bgr_image,
_lang,
)
- ocr_res_list_dict['layout_res'].extend(ocr_result_list)
+ ocr_res_list_dict["layout_res"].extend(ocr_result_list)
# OCR rec
# Create dictionaries to store items by language
@@ -827,8 +785,8 @@ class BatchAnalyze:
for layout_res_item in layout_res:
if not layout_res_item.get("_need_ocr_rec"):
continue
- if 'np_img' in layout_res_item and 'lang' in layout_res_item:
- lang = layout_res_item['lang']
+ if "np_img" in layout_res_item and "lang" in layout_res_item:
+ lang = layout_res_item["lang"]
# Initialize lists for this language if not exist
if lang not in need_ocr_lists_by_lang:
@@ -837,15 +795,14 @@ class BatchAnalyze:
# Add to the appropriate language-specific lists
need_ocr_lists_by_lang[lang].append((layout_res, layout_res_item))
- img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
+ img_crop_lists_by_lang[lang].append(layout_res_item["np_img"])
# Remove temporary fields after collecting
- layout_res_item.pop('np_img', None)
- layout_res_item.pop('lang', None)
- layout_res_item.pop('_need_ocr_rec', None)
+ layout_res_item.pop("np_img", None)
+ layout_res_item.pop("lang", None)
+ layout_res_item.pop("_need_ocr_rec", None)
if len(img_crop_lists_by_lang) > 0:
-
# Process OCR by language
total_processed = 0
@@ -854,39 +811,55 @@ class BatchAnalyze:
if len(img_crop_list) > 0:
# Get OCR results for this language's images
- ocr_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang=lang
- )
- ocr_res_list = run_ocr_rec_inference(
- ocr_model.ocr, img_crop_list, det=False, tqdm_enable=True
- )[0]
+ ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=lang)
+ ocr_res_list = run_ocr_rec_inference(ocr_model.ocr, img_crop_list, det=False, tqdm_enable=True)[0]
# Verify we have matching counts
- assert len(ocr_res_list) == len(
- need_ocr_lists_by_lang[lang]), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}'
+ assert len(ocr_res_list) == len(need_ocr_lists_by_lang[lang]), (
+ f"ocr_res_list: {len(ocr_res_list)},"
+ f" need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}"
+ )
items_to_remove = []
# Process OCR results for this language
for index, (page_layout_res, layout_res_item) in enumerate(need_ocr_lists_by_lang[lang]):
ocr_text, ocr_score = ocr_res_list[index]
- layout_res_item['text'] = ocr_text
- layout_res_item['score'] = float(f"{ocr_score:.3f}")
+ layout_res_item["text"] = ocr_text
+ layout_res_item["score"] = float(f"{ocr_score:.3f}")
should_remove = False
if ocr_score < OcrConfidence.min_confidence:
should_remove = True
else:
- layout_res_bbox = layout_res_item['bbox']
+ layout_res_bbox = layout_res_item["bbox"]
layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]
layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]
if (
- ocr_text in [
- '(204号', '(20', '(2', '(2号', '(20号', '号', '(204',
- '(cid:)', '(ci:)', '(cd:1)', 'cd:)', 'c)', '(cd:)', 'c', 'id:)',
- ':)', '√:)', '√i:)', '−i:)', '−:', 'i:)',
- ]
- and ocr_score < 0.8
- and layout_res_width < layout_res_height
+ ocr_text
+ in [
+ "(204号",
+ "(20",
+ "(2",
+ "(2号",
+ "(20号",
+ "号",
+ "(204",
+ "(cid:)",
+ "(ci:)",
+ "(cd:1)",
+ "cd:)",
+ "c)",
+ "(cd:)",
+ "c",
+ "id:)",
+ ":)",
+ "√:)",
+ "√i:)",
+ "−i:)",
+ "−:",
+ "i:)",
+ ]
+ and ocr_score < 0.8
+ and layout_res_width < layout_res_height
):
should_remove = True
@@ -901,13 +874,13 @@ class BatchAnalyze:
seal_ocr_items = []
for ocr_res_list_dict in ocr_res_list_all_page:
- for layout_res_item in ocr_res_list_dict['layout_res']:
+ for layout_res_item in ocr_res_list_dict["layout_res"]:
if layout_res_item.get("label") == "seal":
seal_ocr_items.append((ocr_res_list_dict, layout_res_item))
seal_ocr_model = None
for ocr_res_list_dict, layout_res_item in tqdm(seal_ocr_items, desc="Seal Predict"):
- np_img = ocr_res_list_dict['np_img']
+ np_img = ocr_res_list_dict["np_img"]
image_h, image_w = np_img.shape[:2]
layout_res_item["text"] = ""
seal_bbox = normalize_to_int_bbox(
@@ -929,9 +902,7 @@ class BatchAnalyze:
)
seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)
- seal_ocr_res = run_ocr_det_inference(
- seal_ocr_model.ocr, seal_crop_bgr, det=True, rec=True
- )[0]
+ seal_ocr_res = run_ocr_det_inference(seal_ocr_model.ocr, seal_crop_bgr, det=True, rec=True)[0]
if not seal_ocr_res:
continue
diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.py
index 9620d5ea..4b40b0b8 100644
--- a/mineru/backend/pipeline/model_init.py
+++ b/mineru/backend/pipeline/model_init.py
@@ -108,7 +108,7 @@ def wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:
return table_model
-def mfr_model_init(weight_dir: str, device: str = "cpu") -> UnimernetModel | FormulaRecognizer:
+def mfr_model_init(weight_dir: str, device: str | torch.device = "cpu") -> UnimernetModel | FormulaRecognizer:
if MFR_MODEL == "unimernet_small":
mfr_model = UnimernetModel(weight_dir, device)
elif MFR_MODEL == "pp_formulanet_plus_m":
@@ -119,7 +119,7 @@ def mfr_model_init(weight_dir: str, device: str = "cpu") -> UnimernetModel | For
return mfr_model
-def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> PPDocLayoutV2LayoutModel:
+def pp_doclayout_v2_model_init(weight: str, device: str | torch.device = "cpu") -> PPDocLayoutV2LayoutModel:
if str(device).startswith("npu"):
device = torch.device(device)
model = PPDocLayoutV2LayoutModel(weight, device)
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 57ac9a54..1fdb4c38 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -99,8 +99,8 @@ def _extract_text_from_block(block: Block) -> str:
text_parts = []
for line in block.lines:
for span in line.spans:
- if span.get("type") == ContentType.TEXT:
- text_parts.append(span.get("content", ""))
+ if span.type == ContentType.TEXT:
+ text_parts.append(span.content)
return "".join(text_parts).strip()
@@ -116,7 +116,7 @@ def _normalize_formula_tag_content(tag_content: str) -> str:
def _get_interline_equation_span(block: Block) -> Span | None:
for line in block.lines:
for span in line.spans:
- if span.get("type") == ContentType.INTERLINE_EQUATION:
+ if span.type == ContentType.INTERLINE_EQUATION:
return span
return None
@@ -125,21 +125,21 @@ def _append_formula_number_tag(equation_block: Block, formula_number_block: Bloc
equation_span = _get_interline_equation_span(equation_block)
tag_content = _normalize_formula_tag_content(_extract_text_from_block(formula_number_block))
if equation_span is not None:
- formula = equation_span.get("content", "")
- equation_span["content"] = f"{formula}\\tag{{{tag_content}}}"
+ formula = equation_span.content
+ equation_span.content = f"{formula}\\tag{{{tag_content}}}"
def _optimize_formula_number_blocks(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
optimized_blocks = []
- blocks = page_info.get("preproc_blocks", [])
+ blocks = page_info.preproc_blocks
for index, block in enumerate(blocks):
- if block.get("type") != BlockType.FORMULA_NUMBER:
+ if block.type != BlockType.FORMULA_NUMBER:
optimized_blocks.append(block)
continue
prev_block = blocks[index - 1] if index > 0 else None
- if prev_block and prev_block.get("type") == BlockType.INTERLINE_EQUATION:
+ if prev_block and prev_block.type == BlockType.INTERLINE_EQUATION:
_append_formula_number_tag(prev_block, block)
continue
@@ -147,16 +147,15 @@ def _optimize_formula_number_blocks(pdf_info_list: list[PageInfo]) -> None:
next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None
if (
next_block
- and next_block.get("type") == BlockType.INTERLINE_EQUATION
- and (next_next_block is None or next_next_block.get("type") != BlockType.FORMULA_NUMBER)
+ and next_block.type == BlockType.INTERLINE_EQUATION
+ and (next_next_block is None or next_next_block.type != BlockType.FORMULA_NUMBER)
):
_append_formula_number_tag(next_block, block)
continue
- block["type"] = BlockType.TEXT
+ block.type = BlockType.TEXT
optimized_blocks.append(block)
-
- page_info["preproc_blocks"] = optimized_blocks
+ page_info.preproc_blocks = optimized_blocks
def _apply_post_ocr(pdf_info_list: list[PageInfo], lang: str | None = None) -> None:
@@ -171,17 +170,17 @@ def _apply_post_ocr(pdf_info_list: list[PageInfo], lang: str | None = None) -> N
def _post_block_process(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
- for block_key in ["preproc_blocks", "para_blocks"]:
- for block in page_info.get(block_key, []):
- block_type = block.get("type")
+ for blocks in [page_info.preproc_blocks, page_info.para_blocks]:
+ for block in blocks:
+ block_type = block.type
if block_type == BlockType.DOC_TITLE:
- block["type"] = BlockType.TITLE
- block["level"] = 1
+ block.type = BlockType.TITLE
+ block.level = 1
elif block_type == BlockType.PARAGRAPH_TITLE:
- block["type"] = BlockType.TITLE
- block["level"] = 2
+ block.type = BlockType.TITLE
+ block.level = 2
elif block_type == BlockType.VERTICAL_TEXT:
- block["type"] = BlockType.TEXT
+ block.type = BlockType.TEXT
def apply_server_side_postprocess(pdf_info_list: list[PageInfo], lang: str | None = None) -> None:
diff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.py
index a5fb8d97..f3178dee 100644
--- a/mineru/backend/pipeline/para_split.py
+++ b/mineru/backend/pipeline/para_split.py
@@ -4,18 +4,13 @@ from __future__ import annotations
import copy
from ...types import Block, PageInfo
-from ...utils.enum_class import BlockType, ContentType, SplitFlag
+from ...utils.enum_class import BlockType, ContentType
from ...utils.language import detect_lang
LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")
LIST_END_FLAG = (".", "。", ";", ";")
-class ListLineTag:
- IS_LIST_START_LINE = "is_list_start_line"
- IS_LIST_END_LINE = "is_list_end_line"
-
-
def __process_blocks(blocks: list[Block]) -> list[Block]:
# 对所有block预处理
# 1.通过title和interline_equation将block分组
@@ -28,14 +23,14 @@ def __process_blocks(blocks: list[Block]) -> list[Block]:
current_block = blocks[i]
# 如果当前块是 text 类型
- if current_block["type"] in [BlockType.TEXT, BlockType.INDEX, BlockType.VERTICAL_TEXT]:
- current_block["bbox_fs"] = copy.deepcopy(current_block["bbox"])
- if "lines" in current_block and len(current_block["lines"]) > 0:
+ if current_block.type in [BlockType.TEXT, BlockType.INDEX, BlockType.VERTICAL_TEXT]:
+ current_block["bbox_fs"] = copy.deepcopy(current_block.bbox)
+ if current_block.lines:
current_block["bbox_fs"] = [
- min([line["bbox"][0] for line in current_block["lines"]]),
- min([line["bbox"][1] for line in current_block["lines"]]),
- max([line["bbox"][2] for line in current_block["lines"]]),
- max([line["bbox"][3] for line in current_block["lines"]]),
+ min([line.bbox[0] for line in current_block.lines]),
+ min([line.bbox[1] for line in current_block.lines]),
+ max([line.bbox[2] for line in current_block.lines]),
+ max([line.bbox[3] for line in current_block.lines]),
]
current_group.append(current_block)
@@ -43,7 +38,7 @@ def __process_blocks(blocks: list[Block]) -> list[Block]:
if i + 1 < len(blocks):
next_block = blocks[i + 1]
# 如果下一个块不是 text 类型且是 title 或 interline_equation 类型
- if next_block["type"] in [
+ if next_block.type in [
BlockType.ABSTRACT,
BlockType.INTERLINE_EQUATION,
BlockType.DOC_TITLE,
@@ -59,12 +54,12 @@ def __process_blocks(blocks: list[Block]) -> list[Block]:
return result
-def __is_list_or_index_block(block: Block) -> bool:
- if block["type"] == BlockType.VERTICAL_TEXT:
+def __is_list_or_index_block(block: Block) -> str:
+ if block.type == BlockType.VERTICAL_TEXT:
return BlockType.VERTICAL_TEXT
- if block["type"] == BlockType.INDEX:
- for line in block["lines"]:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ if block.type == BlockType.INDEX:
+ for line in block.lines:
+ line._is_list_start = True
return BlockType.INDEX
# 一个block如果是list block 应该同时满足以下特征
# 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 右侧不顶格(狗牙状)
@@ -74,9 +69,9 @@ def __is_list_or_index_block(block: Block) -> bool:
# index block 是一种特殊的list block
# 一个block如果是index block 应该同时满足以下特征
# 1.block内有多个line 2.block 内有多个line两侧均顶格写 3.line的开头或者结尾均为数字
- if len(block["lines"]) >= 2:
- first_line = block["lines"][0]
- line_height = first_line["bbox"][3] - first_line["bbox"][1]
+ if len(block.lines) >= 2:
+ first_line = block.lines[0]
+ line_height = first_line.bbox[3] - first_line.bbox[1]
block_weight = block["bbox_fs"][2] - block["bbox_fs"][0]
block_height = block["bbox_fs"][3] - block["bbox_fs"][1]
page_weight, page_height = block["page_size"]
@@ -89,7 +84,7 @@ def __is_list_or_index_block(block: Block) -> bool:
center_close_num = 0
external_sides_not_close_num = 0
multiple_para_flag = False
- last_line = block["lines"][-1]
+ last_line = block.lines[-1]
if page_weight == 0:
block_weight_ratio = 0
@@ -99,21 +94,21 @@ def __is_list_or_index_block(block: Block) -> bool:
# 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
if (
- first_line["bbox"][0] - block["bbox_fs"][0] > line_height / 2
- and abs(last_line["bbox"][0] - block["bbox_fs"][0]) < line_height / 2
- and block["bbox_fs"][2] - last_line["bbox"][2] > line_height
+ first_line.bbox[0] - block["bbox_fs"][0] > line_height / 2
+ and abs(last_line.bbox[0] - block["bbox_fs"][0]) < line_height / 2
+ and block["bbox_fs"][2] - last_line.bbox[2] > line_height
):
multiple_para_flag = True
block_text = ""
- for line in block["lines"]:
+ for line in block.lines:
line_text = ""
- for span in line["spans"]:
- span_type = span["type"]
+ for span in line.spans:
+ span_type = span.type
if span_type == ContentType.TEXT:
- line_text += span["content"].strip()
+ line_text += span.content.strip()
# 添加所有文本,包括空行,保持与block['lines']长度一致
lines_text_list.append(line_text)
block_text = "".join(lines_text_list)
@@ -121,25 +116,25 @@ def __is_list_or_index_block(block: Block) -> bool:
block_lang = detect_lang(block_text)
# logger.info(f"block_lang: {block_lang}")
- for line in block["lines"]:
- line_mid_x = (line["bbox"][0] + line["bbox"][2]) / 2
+ for line in block.lines:
+ line_mid_x = (line.bbox[0] + line.bbox[2]) / 2
block_mid_x = (block["bbox_fs"][0] + block["bbox_fs"][2]) / 2
if (
- line["bbox"][0] - block["bbox_fs"][0] > 0.7 * line_height
- and block["bbox_fs"][2] - line["bbox"][2] > 0.7 * line_height
+ line.bbox[0] - block["bbox_fs"][0] > 0.7 * line_height
+ and block["bbox_fs"][2] - line.bbox[2] > 0.7 * line_height
):
external_sides_not_close_num += 1
if abs(line_mid_x - block_mid_x) < line_height / 2:
center_close_num += 1
# 计算line左侧顶格数量是否大于2,是否顶格用abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height/2 来判断
- if abs(block["bbox_fs"][0] - line["bbox"][0]) < line_height / 2:
+ if abs(block["bbox_fs"][0] - line.bbox[0]) < line_height / 2:
left_close_num += 1
- elif line["bbox"][0] - block["bbox_fs"][0] > line_height:
+ elif line.bbox[0] - block["bbox_fs"][0] > line_height:
left_not_close_num += 1
# 计算右侧是否顶格
- if abs(block["bbox_fs"][2] - line["bbox"][2]) < line_height:
+ if abs(block["bbox_fs"][2] - line.bbox[2]) < line_height:
right_close_num += 1
else:
# 类中文没有超长单词的情况,可以用统一的阈值
@@ -152,7 +147,7 @@ def __is_list_or_index_block(block: Block) -> bool:
closed_area = 0.26 * block_weight
else:
closed_area = 0.36 * block_weight
- if block["bbox_fs"][2] - line["bbox"][2] > closed_area:
+ if block["bbox_fs"][2] - line.bbox[2] > closed_area:
right_not_close_num += 1
# 判断lines_text_list中的元素是否有超过80%都以LIST_END_FLAG结尾
@@ -179,21 +174,21 @@ def __is_list_or_index_block(block: Block) -> bool:
line_end_flag = True
# 有的目录右侧不贴边, 目前认为左边或者右边有一边全贴边,且符合数字规则极为index
- if (left_close_num / len(block["lines"]) >= 0.8 or right_close_num / len(block["lines"]) >= 0.8) and line_num_flag:
- for line in block["lines"]:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ if (left_close_num / len(block.lines) >= 0.8 or right_close_num / len(block.lines) >= 0.8) and line_num_flag:
+ for line in block.lines:
+ line._is_list_start = True
return BlockType.INDEX
# 全部line都居中的特殊list识别,每行都需要换行,特征是多行,且大多数行都前后not_close,每line中点x坐标接近
# 补充条件block的长宽比有要求
elif (
external_sides_not_close_num >= 2
- and center_close_num == len(block["lines"])
- and external_sides_not_close_num / len(block["lines"]) >= 0.5
+ and center_close_num == len(block.lines)
+ and external_sides_not_close_num / len(block.lines) >= 0.5
and block_height / block_weight > 0.4
):
- for line in block["lines"]:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ for line in block.lines:
+ line._is_list_start = True
return BlockType.LIST
elif (
@@ -203,45 +198,45 @@ def __is_list_or_index_block(block: Block) -> bool:
# and block_weight_ratio > 0.27
):
# 处理一种特殊的没有缩进的list,所有行都贴左边,通过右边的空隙判断是否是item尾
- if left_close_num / len(block["lines"]) > 0.8:
+ if left_close_num / len(block.lines) > 0.8:
# 这种是每个item只有一行,且左边都贴边的短item list
- if flag_end_count == 0 and right_close_num / len(block["lines"]) < 0.5:
- for line in block["lines"]:
- if abs(block["bbox_fs"][0] - line["bbox"][0]) < line_height / 2:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ if flag_end_count == 0 and right_close_num / len(block.lines) < 0.5:
+ for line in block.lines:
+ if abs(block["bbox_fs"][0] - line.bbox[0]) < line_height / 2:
+ line._is_list_start = True
# 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
elif line_end_flag:
- for i, line in enumerate(block["lines"]):
+ for i, line in enumerate(block.lines):
if len(lines_text_list[i]) > 0 and lines_text_list[i][-1] in LIST_END_FLAG:
- line[ListLineTag.IS_LIST_END_LINE] = True
- if i + 1 < len(block["lines"]):
- block["lines"][i + 1][ListLineTag.IS_LIST_START_LINE] = True
+ line._is_list_end = True
+ if i + 1 < len(block.lines):
+ block.lines[i + 1]._is_list_start = True
# line item基本没有结束标识符,而且也没有缩进,按右侧空隙判断哪些是item end
else:
line_start_flag = False
- for i, line in enumerate(block["lines"]):
+ for i, line in enumerate(block.lines):
if line_start_flag:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ line._is_list_start = True
line_start_flag = False
- if abs(block["bbox_fs"][2] - line["bbox"][2]) > 0.1 * block_weight:
- line[ListLineTag.IS_LIST_END_LINE] = True
+ if abs(block["bbox_fs"][2] - line.bbox[2]) > 0.1 * block_weight:
+ line._is_list_end = True
line_start_flag = True
# 一种有缩进的特殊有序list,start line 左侧不贴边且以数字开头,end line 以 IS_LIST_END_FLAG 结尾且数量和start line 一致
elif num_start_count >= 2 and num_start_count == flag_end_count:
- for i, line in enumerate(block["lines"]):
+ for i, line in enumerate(block.lines):
if len(lines_text_list[i]) > 0:
if lines_text_list[i][0].isdigit():
- line[ListLineTag.IS_LIST_START_LINE] = True
+ line._is_list_start = True
if lines_text_list[i][-1] in LIST_END_FLAG:
- line[ListLineTag.IS_LIST_END_LINE] = True
+ line._is_list_end = True
else:
# 正常有缩进的list处理
- for line in block["lines"]:
- if abs(block["bbox_fs"][0] - line["bbox"][0]) < line_height / 2:
- line[ListLineTag.IS_LIST_START_LINE] = True
- if abs(block["bbox_fs"][2] - line["bbox"][2]) > line_height:
- line[ListLineTag.IS_LIST_END_LINE] = True
+ for line in block.lines:
+ if abs(block["bbox_fs"][0] - line.bbox[0]) < line_height / 2:
+ line._is_list_start = True
+ if abs(block["bbox_fs"][2] - line.bbox[2]) > line_height:
+ line._is_list_end = True
return BlockType.LIST
else:
@@ -251,27 +246,27 @@ def __is_list_or_index_block(block: Block) -> bool:
def __merge_2_text_blocks(block1: Block, block2: Block) -> Block | None:
- if len(block1["lines"]) > 0 and len(block2["lines"]) > 0:
- first_line = block1["lines"][0]
- line_height = first_line["bbox"][3] - first_line["bbox"][1]
- block1_weight = block1["bbox"][2] - block1["bbox"][0]
- block2_weight = block2["bbox"][2] - block2["bbox"][0]
+ if len(block1.lines) > 0 and len(block2.lines) > 0:
+ first_line = block1.lines[0]
+ line_height = first_line.bbox[3] - first_line.bbox[1]
+ block1_weight = block1.bbox[2] - block1.bbox[0]
+ block2_weight = block2.bbox[2] - block2.bbox[0]
min_block_weight = min(block1_weight, block2_weight)
- if abs(block1["bbox_fs"][0] - first_line["bbox"][0]) < line_height / 2:
- last_line = block2["lines"][-1]
- if len(last_line["spans"]) > 0:
- last_span = last_line["spans"][-1]
- line_height = last_line["bbox"][3] - last_line["bbox"][1]
- if len(first_line["spans"]) > 0:
- first_span = first_line["spans"][0]
- if len(first_span["content"]) > 0:
- span_start_with_num = first_span["content"][0].isdigit()
- span_start_with_big_char = first_span["content"][0].isupper()
+ if abs(block1["bbox_fs"][0] - first_line.bbox[0]) < line_height / 2:
+ last_line = block2.lines[-1]
+ if len(last_line.spans) > 0:
+ last_span = last_line.spans[-1]
+ line_height = last_line.bbox[3] - last_line.bbox[1]
+ if len(first_line.spans) > 0:
+ first_span = first_line.spans[0]
+ if len(first_span.content) > 0:
+ span_start_with_num = first_span.content[0].isdigit()
+ span_start_with_big_char = first_span.content[0].isupper()
if (
# 上一个block的最后一个line的右边界和block的右边界差距不超过line_height
- abs(block2["bbox_fs"][2] - last_line["bbox"][2]) < line_height
+ abs(block2["bbox_fs"][2] - last_line.bbox[2]) < line_height
# 上一个block的最后一个span不是以特定符号结尾
- and not last_span["content"].endswith(LINE_STOP_FLAG)
+ and not last_span.content.endswith(LINE_STOP_FLAG)
# 两个block宽度差距超过2倍也不合并
and abs(block1_weight - block2_weight) < min_block_weight
# 下一个block的第一个字符是数字
@@ -279,66 +274,66 @@ def __merge_2_text_blocks(block1: Block, block2: Block) -> Block | None:
# 下一个block的第一个字符是大写字母
and not span_start_with_big_char
# 下一个块的y0要比上一个块的y1小
- and block1["bbox"][1] < block2["bbox"][3]
+ and block1.bbox[1] < block2.bbox[3]
# 两个块任意一个块需要大于1行
- and (len(block1["lines"]) > 1 or len(block2["lines"]) > 1)
+ and (len(block1.lines) > 1 or len(block2.lines) > 1)
):
if block1["page_num"] != block2["page_num"]:
- for line in block1["lines"]:
- for span in line["spans"]:
- span[SplitFlag.CROSS_PAGE] = True
- block2["lines"].extend(block1["lines"])
- block1["lines"] = []
- block1[SplitFlag.LINES_DELETED] = True
+ for line in block1.lines:
+ for span in line.spans:
+ span._cross_page = True
+ block2.lines.extend(block1.lines)
+ block1.lines = []
+ block1._lines_deleted = True
return block1, block2
def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> Block | None:
- if len(block1["lines"]) > 0 and len(block2["lines"]) > 0:
- first_line = block1["lines"][0]
- line_width = first_line["bbox"][2] - first_line["bbox"][0]
- block1_height = block1["bbox"][3] - block1["bbox"][1]
- block2_height = block2["bbox"][3] - block2["bbox"][1]
+ if len(block1.lines) > 0 and len(block2.lines) > 0:
+ first_line = block1.lines[0]
+ line_width = first_line.bbox[2] - first_line.bbox[0]
+ block1_height = block1.bbox[3] - block1.bbox[1]
+ block2_height = block2.bbox[3] - block2.bbox[1]
min_block_height = min(block1_height, block2_height)
- if line_width > 0 and abs(block1["bbox_fs"][1] - first_line["bbox"][1]) < line_width / 2:
- last_line = block2["lines"][-1]
- if len(last_line["spans"]) > 0:
- last_span = last_line["spans"][-1]
- line_width = last_line["bbox"][2] - last_line["bbox"][0]
- if line_width > 0 and len(first_line["spans"]) > 0:
- first_span = first_line["spans"][0]
+ if line_width > 0 and abs(block1["bbox_fs"][1] - first_line.bbox[1]) < line_width / 2:
+ last_line = block2.lines[-1]
+ if len(last_line.spans) > 0:
+ last_span = last_line.spans[-1]
+ line_width = last_line.bbox[2] - last_line.bbox[0]
+ if line_width > 0 and len(first_line.spans) > 0:
+ first_span = first_line.spans[0]
first_content = first_span.get("content", "")
last_content = last_span.get("content", "")
if len(first_content) > 0:
span_start_with_num = first_content[0].isdigit()
span_start_with_big_char = first_content[0].isupper()
if (
- abs(block2["bbox_fs"][3] - last_line["bbox"][3]) < line_width
+ abs(block2["bbox_fs"][3] - last_line.bbox[3]) < line_width
and not last_content.endswith(LINE_STOP_FLAG)
and abs(block1_height - block2_height) < min_block_height
and not span_start_with_num
and not span_start_with_big_char
):
if block1["page_num"] != block2["page_num"]:
- for line in block1["lines"]:
- for span in line["spans"]:
- span[SplitFlag.CROSS_PAGE] = True
- block2["lines"].extend(block1["lines"])
- block1["lines"] = []
- block1[SplitFlag.LINES_DELETED] = True
+ for line in block1.lines:
+ for span in line.spans:
+ span._cross_page = True
+ block2.lines.extend(block1.lines)
+ block1.lines = []
+ block1._lines_deleted = True
return block1, block2
def __merge_2_list_blocks(block1: Block, block2: Block) -> Block | None:
if block1["page_num"] != block2["page_num"]:
- for line in block1["lines"]:
- for span in line["spans"]:
- span[SplitFlag.CROSS_PAGE] = True
- block2["lines"].extend(block1["lines"])
- block1["lines"] = []
- block1[SplitFlag.LINES_DELETED] = True
+ for line in block1.lines:
+ for span in line.spans:
+ span._cross_page = True
+ block2.lines.extend(block1.lines)
+ block1.lines = []
+ block1._lines_deleted = True
return block1, block2
@@ -347,9 +342,9 @@ def __is_list_group(text_blocks_group: list[Block]) -> bool:
# list group的特征是一个group内的所有block都满足以下条件
# 1.每个block都不超过3行 2. 每个block 的左边界都比较接近(逻辑简单点先不加这个规则)
for block in text_blocks_group:
- if block["type"] == BlockType.VERTICAL_TEXT:
+ if block.type == BlockType.VERTICAL_TEXT:
return False
- if len(block["lines"]) > 3:
+ if len(block.lines) > 3:
return False
return True
@@ -361,7 +356,7 @@ def __para_merge_page(blocks: list[Block]) -> list[Block]:
# 需要先在合并前对所有block判断是否为list or index block
for block in text_blocks_group:
block_type = __is_list_or_index_block(block)
- block["type"] = block_type
+ block.type = block_type
# logger.info(f"{block['type']}:{block}")
if len(text_blocks_group) > 1:
@@ -376,12 +371,12 @@ def __para_merge_page(blocks: list[Block]) -> list[Block]:
if i - 1 >= 0:
prev_block = text_blocks_group[i - 1]
- if current_block["type"] == BlockType.VERTICAL_TEXT and prev_block["type"] == BlockType.VERTICAL_TEXT:
+ if current_block.type == BlockType.VERTICAL_TEXT and prev_block.type == BlockType.VERTICAL_TEXT:
__merge_2_vertical_text_blocks(current_block, prev_block)
- elif current_block["type"] == BlockType.TEXT and prev_block["type"] == BlockType.TEXT and not is_list_group:
+ elif current_block.type == BlockType.TEXT and prev_block.type == BlockType.TEXT and not is_list_group:
__merge_2_text_blocks(current_block, prev_block)
- elif (current_block["type"] == BlockType.LIST and prev_block["type"] == BlockType.LIST) or (
- current_block["type"] == BlockType.INDEX and prev_block["type"] == BlockType.INDEX
+ elif (current_block.type == BlockType.LIST and prev_block.type == BlockType.LIST) or (
+ current_block.type == BlockType.INDEX and prev_block.type == BlockType.INDEX
):
__merge_2_list_blocks(current_block, prev_block)
@@ -404,8 +399,8 @@ def para_split(page_info_list: list[PageInfo]) -> None:
for block in all_blocks:
if "page_num" in block:
if block["page_num"] == page_info["page_idx"]:
- if block["type"] == BlockType.VERTICAL_TEXT:
- block["type"] = BlockType.TEXT
+ if block.type == BlockType.VERTICAL_TEXT:
+ block.type = BlockType.TEXT
page_info["para_blocks"].append(block)
# 从block中删除不需要的page_num和page_size字段
del block["page_num"]
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index 63ab8ade..11d8a7c6 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -43,8 +43,8 @@ class ModelSingleton:
def get_model(
self,
lang: str | None = None,
- formula_enable: bool | None = None,
- table_enable: bool | None = None,
+ formula_enable: bool = True,
+ table_enable: bool = True,
) -> MineruPipelineModel:
key = (lang, formula_enable, table_enable)
with self._lock:
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 68ca5b5b..a3142fb3 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -20,7 +20,6 @@ from ...utils.visual_magic_model_utils import (
fallback_leading_table_continuation_captions,
find_best_visual_parent,
)
-from .para_split import ListLineTag
from .pipeline_middle_json_mkcontent import _merge_para_text
if TYPE_CHECKING:
@@ -139,11 +138,11 @@ class MagicModel:
@staticmethod
def __fix_text_block(block: Block) -> Block:
- if block["type"] == BlockType.TEXT and is_vertical_text_block_by_spans(block["spans"]):
+ if block.type == BlockType.TEXT and is_vertical_text_block_by_spans(block["spans"]):
# layout 偶发会把竖排正文识别为横排 text,这里用旧版 span 高宽比规则兜底。
- block["type"] = BlockType.VERTICAL_TEXT
+ block.type = BlockType.VERTICAL_TEXT
- if block["type"] == BlockType.VERTICAL_TEXT:
+ if block.type == BlockType.VERTICAL_TEXT:
# 如果是纵向文本块,则按纵向lines处理
block_lines = merge_spans_to_vertical_line(block["spans"])
sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)
@@ -151,16 +150,16 @@ class MagicModel:
block_lines = merge_spans_to_line(block["spans"])
sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
- if block["type"] == BlockType.CODE:
+ if block.type == BlockType.CODE:
for line in sort_block_lines:
- line[ListLineTag.IS_LIST_START_LINE] = True
+ line._is_list_start = True
code_content = _merge_para_text({"lines": sort_block_lines}, False, "\n")
guess_lang = guess_language_by_text(code_content)
if guess_lang not in ["txt", "unknown"]:
block["sub_type"] = "code"
block["guess_lang"] = guess_lang
- block["lines"] = sort_block_lines
+ block.lines = sort_block_lines
del block["spans"]
return block
@@ -256,7 +255,7 @@ class MagicModel:
ContentType.CHART,
ContentType.INTERLINE_EQUATION,
]:
- span = Span(type=span_type, bbox=block["bbox"])
+ span = Span(type=span_type, bbox=block.bbox)
if span_type == ContentType.IMAGE and block.get("sub_type") == "seal":
seal_text = self.__normalize_seal_text(block.get("text"))
if seal_text:
@@ -272,17 +271,17 @@ class MagicModel:
self.all_image_spans.append(span)
# 构造line对象
spans = [span]
- line = Line(spans=spans, bbox=block["bbox"])
- block["lines"] = [line]
+ line = Line(spans=spans, bbox=block.bbox)
+ block.lines = [line]
else:
# span填充
- if block["type"] == BlockType.FORMULA_NUMBER:
+ if block.type == BlockType.FORMULA_NUMBER:
block_spans = span_matcher.collect_for_block(
- block["bbox"],
+ block.bbox,
overlap_ratio_getter=self.__formula_number_overlap_ratio,
)
else:
- block_spans = span_matcher.collect_for_block(block["bbox"])
+ block_spans = span_matcher.collect_for_block(block.bbox)
block["spans"] = block_spans
block = self.__fix_text_block(block)
@@ -350,14 +349,14 @@ class MagicModel:
return
ordered_blocks = sorted(self.page_blocks, key=lambda x: x["index"])
- original_type_by_index = {block["index"]: block["type"] for block in ordered_blocks}
- position_by_index = {block["index"]: pos for pos, block in enumerate(ordered_blocks)}
- main_blocks = [block for block in ordered_blocks if original_type_by_index[block["index"]] in self.VISUAL_MAIN_TYPES]
- child_blocks = [block for block in ordered_blocks if original_type_by_index[block["index"]] in self.VISUAL_CHILD_TYPES]
+ original_type_by_index = {block.index: block.type for block in ordered_blocks}
+ position_by_index = {block.index: pos for pos, block in enumerate(ordered_blocks)}
+ main_blocks = [block for block in ordered_blocks if original_type_by_index[block.index] in self.VISUAL_MAIN_TYPES]
+ child_blocks = [block for block in ordered_blocks if original_type_by_index[block.index] in self.VISUAL_CHILD_TYPES]
child_parent_map: dict[int, int | None] = {}
grouped_children: dict[int, dict[str, list[Block]]] = {
- main_block["index"]: {"captions": [], "footnotes": []} for main_block in main_blocks
+ main_block.index: {"captions": [], "footnotes": []} for main_block in main_blocks
}
for child_block in child_blocks:
@@ -368,22 +367,22 @@ class MagicModel:
original_type_by_index,
position_by_index,
)
- child_parent_map[child_block["index"]] = None if parent_block is None else parent_block["index"]
+ child_parent_map[child_block.index] = None if parent_block is None else parent_block.index
for child_block in child_blocks:
- original_child_type = original_type_by_index[child_block["index"]]
- parent_index = child_parent_map[child_block["index"]]
+ original_child_type = original_type_by_index[child_block.index]
+ parent_index = child_parent_map[child_block.index]
if parent_index is None:
- child_block["type"] = BlockType.TEXT
- self.__sync_layout_det_type(child_block["index"], BlockType.TEXT)
+ child_block.type = BlockType.TEXT
+ self.__sync_layout_det_type(child_block.index, BlockType.TEXT)
continue
parent_type = original_type_by_index[parent_index]
child_kind = self.__child_kind(original_child_type)
mapped_type = self.VISUAL_TYPE_MAPPING[parent_type][child_kind]
- child_block["type"] = mapped_type
- self.__sync_layout_det_type(child_block["index"], mapped_type)
+ child_block.type = mapped_type
+ self.__sync_layout_det_type(child_block.index, mapped_type)
grouped_children[parent_index][f"{child_kind}s"].append(child_block)
self.image_groups = []
@@ -392,10 +391,10 @@ class MagicModel:
rebuilt_page_blocks: list[Block] = []
for block in ordered_blocks:
- original_block_type = original_type_by_index[block["index"]]
+ original_block_type = original_type_by_index[block.index]
if original_block_type in self.VISUAL_CHILD_TYPES:
- if child_parent_map[block["index"]] is None:
+ if child_parent_map[block.index] is None:
rebuilt_page_blocks.append(block)
continue
@@ -408,21 +407,18 @@ class MagicModel:
if original_block_type in [BlockType.IMAGE, BlockType.CHART]:
body_block.pop("sub_type", None)
captions = sorted(
- [
- self.__make_child_block(caption, mapping["caption"])
- for caption in grouped_children[block["index"]]["captions"]
- ],
+ [self.__make_child_block(caption, mapping["caption"]) for caption in grouped_children[block.index]["captions"]],
key=lambda x: x["index"],
)
footnotes = sorted(
[
self.__make_child_block(footnote, mapping["footnote"])
- for footnote in grouped_children[block["index"]]["footnotes"]
+ for footnote in grouped_children[block.index]["footnotes"]
],
key=lambda x: x["index"],
)
- self.__sync_layout_det_type(block["index"], mapping["body"])
+ self.__sync_layout_det_type(block.index, mapping["body"])
group_info = {
f"{original_block_type}_body": body_block,
@@ -438,10 +434,10 @@ class MagicModel:
two_layer_block = Block(
type=original_block_type,
- bbox=block["bbox"],
+ bbox=block.bbox,
blocks=[body_block, *captions, *footnotes],
)
- two_layer_block["index"] = block["index"]
+ two_layer_block.index = block.index
if block.get("score"):
two_layer_block["score"] = block["score"]
if original_block_type in [BlockType.IMAGE, BlockType.CHART] and block.get("sub_type"):
@@ -460,7 +456,7 @@ class MagicModel:
original_type_by_index: dict[int, str],
position_by_index: dict[int, int],
) -> Block | None:
- child_type = original_type_by_index[child_block["index"]]
+ child_type = original_type_by_index[child_block.index]
if child_type not in self.VISUAL_CHILD_TYPES:
return None
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index 4380587b..85158e3c 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -13,23 +13,22 @@ from ...utils.config_reader import get_latex_delimiter_config
from ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode
from ...utils.language import detect_lang
from ..utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
-from .para_split import ListLineTag
-def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_buket_path: str = "") -> str:
+def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_buket_path: str = "") -> list[str]:
page_markdown = []
for para_block in paras_of_layout:
para_text = ""
- para_type = para_block["type"]
+ para_type = para_block.type
if para_type in [BlockType.TEXT, BlockType.LIST, BlockType.INDEX, BlockType.ABSTRACT, BlockType.REF_TEXT]:
para_text = merge_para_with_text(para_block)
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
para_text = f"{'#' * title_level} {merge_para_with_text(para_block)}"
elif para_type == BlockType.INTERLINE_EQUATION:
- if len(para_block["lines"]) == 0 or len(para_block["lines"][0]["spans"]) == 0:
+ if len(para_block.lines) == 0 or len(para_block.lines[0].spans) == 0:
continue
- if para_block["lines"][0]["spans"][0].get("content", ""):
+ if para_block.lines[0].spans[0].get("content", ""):
para_text = merge_para_with_text(para_block)
else:
para_text = f"![]({img_buket_path}/{para_block['lines'][0]['spans'][0]['image_path']})"
@@ -95,9 +94,9 @@ def get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:
def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> None:
# pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。
# markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。
- if block.get("type") != BlockType.CODE_BODY:
+ if block.type != BlockType.CODE_BODY:
return block
- if parent_block.get("type") != BlockType.CODE:
+ if parent_block.type != BlockType.CODE:
return block
needs_sub_type = "sub_type" not in block and "sub_type" in parent_block
@@ -113,11 +112,13 @@ def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> N
return render_block
-def render_visual_block_segments(block: Block, img_buket_path: str = "", para_block: Block | None = None) -> list[str]:
+def render_visual_block_segments(
+ block: Block, img_buket_path: str = "", para_block: Block | None = None
+) -> list[tuple[str, str]]:
# 将单个视觉子 block 渲染成一个或多个 segment。
# 文本类子块统一输出 markdown_line;
# table 的 html 输出为 html_block,供后续决定是否需要空行隔开。
- block_type = block["type"]
+ block_type = block.type
if block_type in [
BlockType.IMAGE_CAPTION,
@@ -137,9 +138,9 @@ def render_visual_block_segments(block: Block, img_buket_path: str = "", para_bl
if block_type == BlockType.IMAGE_BODY:
rendered_segments = []
- for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] != ContentType.IMAGE:
+ for line in block.lines:
+ for span in line.spans:
+ if span.type != ContentType.IMAGE:
continue
if span.get("image_path", ""):
rendered_segments.append(
@@ -159,21 +160,21 @@ def render_visual_block_segments(block: Block, img_buket_path: str = "", para_bl
if block_type == BlockType.CHART_BODY:
return [
(f"![]({img_buket_path}/{span['image_path']})", "markdown_line")
- for line in block["lines"]
- for span in line["spans"]
- if span["type"] == ContentType.CHART and span.get("image_path", "")
+ for line in block.lines
+ for span in line.spans
+ if span.type == ContentType.CHART and span.get("image_path", "")
]
if block_type == BlockType.TABLE_BODY:
rendered_segments = []
- for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] != ContentType.TABLE:
+ for line in block.lines:
+ for span in line.spans:
+ if span.type != ContentType.TABLE:
continue
if span.get("html", ""):
rendered_segments.append(
(
- _format_embedded_html(span["html"], img_buket_path),
+ _format_embedded_html(span.html, img_buket_path),
"html_block",
)
)
@@ -184,7 +185,7 @@ def render_visual_block_segments(block: Block, img_buket_path: str = "", para_bl
return []
-def get_visual_block_separator(prev_segment_kind: str, current_segment_kind: str) -> str:
+def get_visual_block_separator(prev_segment_kind: str | None, current_segment_kind: str) -> str:
# 根据前后 segment 类型决定分隔符:
# 1. 普通 markdown 行之间用 hard break(" \\n")
# 2. 进入 html block 前只换一行
@@ -264,7 +265,7 @@ def _build_visual_details_block(content: str, summary: str) -> str:
def _apply_visual_sub_type(para_content: str, para_block: Block) -> str:
"""将视觉父块的 sub_type 透传到 content_list 输出顶层。"""
- sub_type = para_block.get("sub_type")
+ sub_type = para_block.sub_type
if sub_type:
para_content["sub_type"] = sub_type
@@ -283,7 +284,7 @@ def merge_para_with_text(para_block: Block) -> str:
return f"```{guess_lang}\n{code_text}\n```"
para_text = _merge_para_text(para_block)
- if para_block.get("type") == BlockType.TEXT:
+ if para_block.type == BlockType.TEXT:
para_text = escape_text_block_markdown_prefix(para_text)
return para_text
@@ -297,12 +298,12 @@ def _merge_para_text(para_block: Block, escape_markdown: bool = True, list_line_
block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
para_parts = []
- for line_idx, line in enumerate(para_block["lines"]):
+ for line_idx, line in enumerate(para_block.lines):
line_prefix = _line_prefix(line_idx, line, list_line_break)
if line_prefix:
para_parts.append(line_prefix)
- for span_idx, span in enumerate(line["spans"]):
+ for span_idx, span in enumerate(line.spans):
rendered_span = _render_span(span, escape_markdown=escape_markdown)
if rendered_span is None:
continue
@@ -325,16 +326,16 @@ def _merge_para_text(para_block: Block, escape_markdown: bool = True, list_line_
def _is_fenced_code_block(para_block: Block) -> bool:
- return para_block.get("type") == BlockType.CODE_BODY and para_block.get("sub_type") == BlockType.CODE
+ return para_block.type == BlockType.CODE_BODY and para_block.sub_type == BlockType.CODE
def _collect_text_for_lang_detection(para_block: Block) -> str:
# 只收集 TEXT span 的内容,用于语言检测。
# 这里会先做全角转半角,但不会修改原始输入数据。
block_text_parts = []
- for line in para_block["lines"]:
- for span in line["spans"]:
- if span["type"] == ContentType.TEXT:
+ for line in para_block.lines:
+ for span in line.spans:
+ if span.type == ContentType.TEXT:
block_text_parts.append(_normalize_text_content(span.get("content", "")))
return "".join(block_text_parts)
@@ -348,7 +349,7 @@ def _normalize_text_content(content: str) -> str:
def _render_span(span: Span, escape_markdown: bool = True) -> str:
# 将单个 span 渲染成 markdown 片段。
# 这里只负责“渲染成什么文本”,不决定后面是否补空格。
- span_type = span["type"]
+ span_type = span.type
content = ""
if span_type == ContentType.TEXT:
@@ -382,7 +383,7 @@ def _join_rendered_span(
if span_type == ContentType.INTERLINE_EQUATION:
return content, ""
- is_last_span = span_idx == len(line["spans"]) - 1
+ is_last_span = span_idx == len(line.spans) - 1
if block_lang in CJK_LANGS:
if is_last_span and span_type != ContentType.INLINE_EQUATION:
@@ -403,7 +404,7 @@ def _join_rendered_span(
def _line_prefix(line_idx: int, line: Line, list_line_break: str = " \n") -> str:
# 处理进入新 list item 前的 block 级换行。
# 这里保留历史语义:list 起始行前插入一个 hard break。
- if line_idx >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
+ if line_idx >= 1 and line._is_list_start:
return list_line_break
return ""
@@ -411,15 +412,15 @@ def _line_prefix(line_idx: int, line: Line, list_line_break: str = " \n") -> st
def _next_line_starts_with_lowercase_text(para_block: Block, line_idx: int) -> bool:
# 判断下一行是否以小写英文文本开头。
# 这个条件用于决定西文行尾的连字符是否应与下一行合并。
- if line_idx + 1 >= len(para_block["lines"]):
+ if line_idx + 1 >= len(para_block.lines):
return False
- next_line_spans = para_block["lines"][line_idx + 1].get("spans")
+ next_line_spans = para_block.lines[line_idx + 1].spans
if not next_line_spans:
return False
next_span = next_line_spans[0]
- if next_span.get("type") != ContentType.TEXT:
+ if next_span.type != ContentType.TEXT:
return False
next_content = _normalize_text_content(next_span.get("content", ""))
@@ -447,7 +448,7 @@ def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list
ref_group = []
for para_block in para_blocks or []:
- if para_block.get("type") == BlockType.REF_TEXT:
+ if para_block.type == BlockType.REF_TEXT:
ref_group.append(para_block)
continue
@@ -481,7 +482,7 @@ def _split_list_item_blocks(para_block: Block) -> list[Block]:
current_lines = []
for line_idx, line in enumerate(para_block.lines):
- if line_idx > 0 and line.get(ListLineTag.IS_LIST_START_LINE, False) and current_lines:
+ if line_idx > 0 and line._is_list_start and current_lines:
item_blocks.append(
{
"type": BlockType.TEXT,
@@ -506,7 +507,7 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
for line in lines:
for span in line.spans:
- span_type = span.get("type")
+ span_type = span.type
if span_type == ContentType.TABLE:
return span.get("image_path", ""), span.get("html", "")
if span_type == ContentType.CHART:
@@ -518,8 +519,8 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
return "", ""
if "blocks" in para_block:
- for block in para_block["blocks"]:
- block_type = block.get("type")
+ for block in para_block.blocks:
+ block_type = block.type
if block_type in [
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
@@ -537,11 +538,11 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
def merge_para_with_text_v2(para_block: Block) -> str:
block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
para_content = []
- para_type = para_block.get("type")
+ para_type = para_block.type
for line_idx, line in enumerate(para_block.lines):
for span_idx, span in enumerate(line.spans):
- span_type = span.get("type")
+ span_type = span.type
if span_type == ContentType.TEXT:
content = _normalize_text_content(span.get("content", ""))
@@ -549,7 +550,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
continue
output_type = ContentTypeV2.SPAN_PHONETIC if para_type == BlockType.PHONETIC else ContentTypeV2.SPAN_TEXT
- is_last_span = span_idx == len(line["spans"]) - 1
+ is_last_span = span_idx == len(line.spans) - 1
if block_lang in CJK_LANGS:
rendered_content = content if is_last_span else f"{content} "
@@ -596,7 +597,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
def make_blocks_to_content_list(
para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]
) -> list[dict[str, Any]]:
- para_type = para_block["type"]
+ para_type = para_block.type
para_content = None
if para_type in [
BlockType.TEXT,
@@ -638,13 +639,13 @@ def make_blocks_to_content_list(
if title_level != 0:
para_content["text_level"] = title_level
elif para_type == BlockType.INTERLINE_EQUATION:
- if len(para_block["lines"]) == 0 or len(para_block["lines"][0]["spans"]) == 0:
+ if len(para_block.lines) == 0 or len(para_block.lines[0]["spans"]) == 0:
return None
para_content = {
"type": ContentType.EQUATION,
"img_path": f"{img_buket_path}/{para_block['lines'][0]['spans'][0].get('image_path', '')}",
}
- if para_block["lines"][0]["spans"][0].get("content", ""):
+ if para_block.lines[0]["spans"][0].get("content", ""):
para_content["text"] = merge_para_with_text(para_block)
para_content["text_format"] = "latex"
elif para_type == BlockType.IMAGE:
@@ -655,24 +656,24 @@ def make_blocks_to_content_list(
if image_content:
para_content["content"] = image_content
_apply_visual_sub_type(para_content, para_block)
- for block in para_block["blocks"]:
- if block["type"] == BlockType.IMAGE_BODY:
+ for block in para_block.blocks:
+ if block.type == BlockType.IMAGE_BODY:
for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] == ContentType.IMAGE:
+ for span in line.spans:
+ if span.type == ContentType.IMAGE:
if span.get("image_path", ""):
para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
- if block["type"] == BlockType.IMAGE_CAPTION:
+ if block.type == BlockType.IMAGE_CAPTION:
para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.IMAGE_FOOTNOTE:
+ if block.type == BlockType.IMAGE_FOOTNOTE:
para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.TABLE:
para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
- for block in para_block["blocks"]:
- if block["type"] == BlockType.TABLE_BODY:
+ for block in para_block.blocks:
+ if block.type == BlockType.TABLE_BODY:
for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] == ContentType.TABLE:
+ for span in line.spans:
+ if span.type == ContentType.TABLE:
if span.get("html", ""):
para_content[BlockType.TABLE_BODY] = _format_embedded_html(
span["html"],
@@ -682,9 +683,9 @@ def make_blocks_to_content_list(
if span.get("image_path", ""):
para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
- if block["type"] == BlockType.TABLE_CAPTION:
+ if block.type == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.TABLE_FOOTNOTE:
+ if block.type == BlockType.TABLE_FOOTNOTE:
para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.CHART:
para_content = {
@@ -695,14 +696,14 @@ def make_blocks_to_content_list(
BlockType.CHART_FOOTNOTE: [],
}
for block in para_block.blocks:
- if block["type"] == BlockType.CHART_BODY:
+ if block.type == BlockType.CHART_BODY:
for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] == ContentType.CHART and span.get("image_path", ""):
+ for span in line.spans:
+ if span.type == ContentType.CHART and span.get("image_path", ""):
para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
- if block["type"] == BlockType.CHART_CAPTION:
+ if block.type == BlockType.CHART_CAPTION:
para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.CHART_FOOTNOTE:
+ if block.type == BlockType.CHART_FOOTNOTE:
para_content[BlockType.CHART_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.CODE:
para_content = {
@@ -713,11 +714,11 @@ def make_blocks_to_content_list(
}
for block in para_block.blocks:
render_block = _inherit_parent_code_render_metadata(block, para_block)
- if block["type"] == BlockType.CODE_BODY:
+ if block.type == BlockType.CODE_BODY:
para_content[BlockType.CODE_BODY] = merge_para_with_text(render_block)
- if block["type"] == BlockType.CODE_CAPTION:
+ if block.type == BlockType.CODE_CAPTION:
para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.CODE_FOOTNOTE:
+ if block.type == BlockType.CODE_FOOTNOTE:
para_content[BlockType.CODE_FOOTNOTE].append(merge_para_with_text(block))
if not para_content:
@@ -732,7 +733,7 @@ def make_blocks_to_content_list(
def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> list[dict[str, Any]]:
- para_type = para_block["type"]
+ para_type = para_block.type
para_content = None
if para_type in [
@@ -802,9 +803,9 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
image_footnote = []
image_path, image_content = _get_body_data(para_block)
for block in para_block.blocks:
- if block["type"] == BlockType.IMAGE_CAPTION:
+ if block.type == BlockType.IMAGE_CAPTION:
image_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.IMAGE_FOOTNOTE:
+ if block.type == BlockType.IMAGE_FOOTNOTE:
image_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.IMAGE,
@@ -814,7 +815,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"image_footnote": image_footnote,
},
}
- if image_content or para_block.get("sub_type"):
+ if image_content or para_block.sub_type:
para_content["content"]["content"] = image_content
_apply_visual_sub_type(para_content, para_block)
elif para_type == BlockType.TABLE:
@@ -828,9 +829,9 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
else:
table_type = ContentTypeV2.TABLE_SIMPLE
for block in para_block.blocks:
- if block["type"] == BlockType.TABLE_CAPTION:
+ if block.type == BlockType.TABLE_CAPTION:
table_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.TABLE_FOOTNOTE:
+ if block.type == BlockType.TABLE_FOOTNOTE:
table_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.TABLE,
@@ -848,9 +849,9 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
chart_footnote = []
image_path, _ = _get_body_data(para_block)
for block in para_block.blocks:
- if block["type"] == BlockType.CHART_CAPTION:
+ if block.type == BlockType.CHART_CAPTION:
chart_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.CHART_FOOTNOTE:
+ if block.type == BlockType.CHART_FOOTNOTE:
chart_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.CHART,
@@ -866,11 +867,11 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
code_footnote = []
code_content = []
for block in para_block.blocks:
- if block["type"] == BlockType.CODE_CAPTION:
+ if block.type == BlockType.CODE_CAPTION:
code_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.CODE_FOOTNOTE:
+ if block.type == BlockType.CODE_FOOTNOTE:
code_footnote.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.CODE_BODY:
+ if block.type == BlockType.CODE_BODY:
code_content = merge_para_with_text_v2(block)
sub_type = para_block["sub_type"]
diff --git a/mineru/backend/utils/html_image_utils.py b/mineru/backend/utils/html_image_utils.py
index 973be9a7..e84daed6 100644
--- a/mineru/backend/utils/html_image_utils.py
+++ b/mineru/backend/utils/html_image_utils.py
@@ -71,7 +71,7 @@ def _write_image_once(image_writer: DataWriter, img_path: str, img_bytes: bytes)
written_paths.add(img_path)
-def save_base64_image(b64_data_uri: str, image_writer: DataWriter, page_index: int) -> str | None:
+def _save_base64_image(b64_data_uri: str, image_writer: DataWriter, page_index: int) -> str | None:
"""Persist a data-URI image via image_writer and return a relative path."""
if not image_writer:
return None
@@ -102,13 +102,13 @@ def save_base64_image(b64_data_uri: str, image_writer: DataWriter, page_index: i
return img_path
-def replace_inline_base64_img_src(markup: str, image_writer: DataWriter, page_index: int) -> str:
+def _replace_inline_base64_img_src(markup: str, image_writer: DataWriter, page_index: int) -> str:
"""Replace inline base64 image sources in HTML-like markup with local paths."""
if not markup or not image_writer or "base64," not in markup:
return markup
def _replace_src(match: re.Match[str], _writer: DataWriter = image_writer, _idx: int = page_index) -> str:
- img_path = save_base64_image(match.group(1), _writer, _idx)
+ img_path = _save_base64_image(match.group(1), _writer, _idx)
if img_path:
return f'src="{img_path}"'
return match.group(0)
@@ -122,7 +122,7 @@ def replace_inline_base64_img_src(markup: str, image_writer: DataWriter, page_in
def replace_inline_table_images(
blocks: list[Block],
- image_writer: DataWriter,
+ image_writer: DataWriter | None,
page_index: int,
table_block_type: str = BlockType.TABLE,
table_body_type: str = BlockType.TABLE_BODY,
@@ -144,30 +144,17 @@ def replace_inline_table_images(
for span in line.spans:
if span.type != table_span_type:
continue
- span.html = replace_inline_base64_img_src(
+ span.html = _replace_inline_base64_img_src(
span.html,
image_writer,
page_index,
)
-def save_span_image_if_needed(
- span: Span,
- image_writer: DataWriter,
- page_index: int,
- source_key: str = "image_base64",
- target_key: str = "image_path",
-) -> None:
+def save_span_image_if_needed(span: Span, image_writer: DataWriter, page_index: int) -> None:
"""Persist a span-level base64 image and normalize the target path field."""
- image_base64 = span.get(source_key, "")
- if not image_base64:
- span.setdefault(target_key, "")
- return
-
- img_path = save_base64_image(image_base64, image_writer, page_index)
- if img_path:
- span[target_key] = img_path
- del span[source_key]
- return
-
- span.setdefault(target_key, "")
+ if span.image_base64:
+ image_path = _save_base64_image(span.image_base64, image_writer, page_index)
+ if image_path:
+ span.image_path = image_path
+ span.image_base64 = ""
diff --git a/mineru/backend/utils/markdown_utils.py b/mineru/backend/utils/markdown_utils.py
index f5de61f2..e29d6efe 100644
--- a/mineru/backend/utils/markdown_utils.py
+++ b/mineru/backend/utils/markdown_utils.py
@@ -3,9 +3,7 @@
import re
CONSERVATIVE_MARKDOWN_SPECIAL_CHARS = ("*", "_", "`", "~", "$")
-TEXT_BLOCK_MARKDOWN_PREFIX_RE = re.compile(
- r"^(?P<indent>[ \t]{0,3})(?P<marker>#{1,6}|[+-])(?=[ \t])"
-)
+TEXT_BLOCK_MARKDOWN_PREFIX_RE = re.compile(r"^(?P<indent>[ \t]{0,3})(?P<marker>#{1,6}|[+-])(?=[ \t])")
def escape_conservative_markdown_text(content: str) -> str:
@@ -22,10 +20,7 @@ def escape_conservative_markdown_text(content: str) -> str:
preceding_backslashes += 1
continue
- if (
- char in CONSERVATIVE_MARKDOWN_SPECIAL_CHARS
- and preceding_backslashes % 2 == 0
- ):
+ if char in CONSERVATIVE_MARKDOWN_SPECIAL_CHARS and preceding_backslashes % 2 == 0:
escaped_chars.append("\\")
escaped_chars.append(char)
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 0928c9ca..9fa01b27 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -28,7 +28,7 @@ def build_middle_json(
image_writer: DataWriter,
*,
init_fn: Callable[..., dict[str, Any]],
- page_cvt_fn: Callable[[T], PageInfo],
+ page_cvt_fn: Callable[[T, dict, Any, DataWriter | None, int], PageInfo],
finalize_fn: Callable[..., None],
**kwargs: Any,
) -> dict[str, Any]:
@@ -117,8 +117,8 @@ def apply_post_ocr(pdf_info_list: list[PageInfo], ocr_model: Any) -> None:
img_crop_list = []
for page_info in pdf_info_list:
- for blocks_key in ("preproc_blocks", "discarded_blocks"):
- for block in page_info.get(blocks_key, []):
+ for blocks in [page_info.preproc_blocks, page_info.discarded_blocks]:
+ for block in blocks:
for span in _iter_block_spans(block):
if "np_img" in span:
need_ocr_list.append(span)
diff --git a/mineru/backend/utils/ocr_det_utils.py b/mineru/backend/utils/ocr_det_utils.py
index 175c110a..85e9327e 100644
--- a/mineru/backend/utils/ocr_det_utils.py
+++ b/mineru/backend/utils/ocr_det_utils.py
@@ -11,39 +11,39 @@ from ...utils.pdf_image_tools import get_crop_img
OCR_DET_PADDING = 50
-def get_ch_lite_ocr_det_model() -> Any:
- try:
- from ..pipeline.model_init import AtomModelSingleton
- except Exception as e:
- logger.error(
- "Failed to import AtomModelSingleton, OCR detection will not work. If you want to use OCR features, "
- "please execute `pip install mineru[core]` to install the required packages."
- )
- raise e
-
- atom_model_manager = AtomModelSingleton()
- return atom_model_manager.get_atom_model(atom_model_name="ocr", ocr_show_log=False, det_db_box_thresh=0.3, lang="ch_lite")
-
-
-def detect_ocr_boxes_from_padded_crop(
- bbox: list[float], page_pil_img: Any, scale: float, ocr_model: Any = None, padding: int = OCR_DET_PADDING
-) -> tuple[list[dict[str, Any]], int]:
- if not bbox:
- return [], padding
-
- crop_pil_img = get_crop_img(bbox, page_pil_img, scale)
- crop_np_img = np.array(crop_pil_img)
- if crop_np_img.size == 0:
- return [], padding
-
- if padding > 0:
- crop_np_img = cv2.copyMakeBorder(
- crop_np_img, padding, padding, padding, padding, cv2.BORDER_CONSTANT, value=[255, 255, 255]
- )
-
- crop_img = cv2.cvtColor(crop_np_img, cv2.COLOR_RGB2BGR)
- if ocr_model is None:
- ocr_model = get_ch_lite_ocr_det_model()
-
- ocr_det_res = ocr_model.ocr(crop_img, rec=False)[0]
- return ocr_det_res or [], padding
+# def get_ch_lite_ocr_det_model() -> Any:
+# try:
+# from ..pipeline.model_init import AtomModelSingleton
+# except Exception as e:
+# logger.error(
+# "Failed to import AtomModelSingleton, OCR detection will not work. If you want to use OCR features, "
+# "please execute `pip install mineru[core]` to install the required packages."
+# )
+# raise e
+#
+# atom_model_manager = AtomModelSingleton()
+# return atom_model_manager.get_atom_model(atom_model_name="ocr", ocr_show_log=False, det_db_box_thresh=0.3, lang="ch_lite")
+
+
+# def detect_ocr_boxes_from_padded_crop(
+# bbox: list[float], page_pil_img: Any, scale: float, ocr_model: Any = None, padding: int = OCR_DET_PADDING
+# ) -> tuple[list[dict[str, Any]], int]:
+# if not bbox:
+# return [], padding
+#
+# crop_pil_img = get_crop_img(bbox, page_pil_img, scale)
+# crop_np_img = np.array(crop_pil_img)
+# if crop_np_img.size == 0:
+# return [], padding
+#
+# if padding > 0:
+# crop_np_img = cv2.copyMakeBorder(
+# crop_np_img, padding, padding, padding, padding, cv2.BORDER_CONSTANT, value=[255, 255, 255]
+# )
+#
+# crop_img = cv2.cvtColor(crop_np_img, cv2.COLOR_RGB2BGR)
+# if ocr_model is None:
+# ocr_model = get_ch_lite_ocr_det_model()
+#
+# ocr_det_res = ocr_model.ocr(crop_img, rec=False)[0]
+# return ocr_det_res or [], padding
diff --git a/mineru/backend/utils/office_chart.py b/mineru/backend/utils/office_chart.py
index 1dd4c172..7b2ba157 100644
--- a/mineru/backend/utils/office_chart.py
+++ b/mineru/backend/utils/office_chart.py
@@ -1,4 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import math
from dataclasses import dataclass, field
from datetime import date, datetime, time
@@ -10,7 +12,8 @@ from lxml import etree
from openpyxl import load_workbook
from openpyxl.utils.cell import range_to_tuple
from openpyxl.utils.datetime import MAC_EPOCH, WINDOWS_EPOCH, from_excel
-
+from openpyxl.workbook.workbook import Workbook
+from openpyxl.worksheet.worksheet import Worksheet
_CHART_NS: Final = "http://schemas.openxmlformats.org/drawingml/2006/chart"
_DRAWING_NS: Final = "http://schemas.openxmlformats.org/drawingml/2006/main"
@@ -89,7 +92,7 @@ def html_table_from_excel_bytes(excel_bytes: bytes) -> str:
return ""
-def _extract_non_empty_worksheet_rows(worksheet: object) -> list[list[str]]:
+def _extract_non_empty_worksheet_rows(worksheet: Worksheet) -> list[list[str]]:
"""提取工作表中首尾有内容的行,避免空 sheet 或尾部空列撑大兜底表格。"""
raw_rows: list[list[str]] = []
for row in worksheet.iter_rows(values_only=True):
@@ -200,10 +203,7 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:
return None
has_date_axis = plot_area.find("c:dateAx", namespaces=_NS) is not None
- plot_kinds = {
- _plot_kind_from_tag_name(tag_name, has_date_axis)
- for tag_name, _ in plot_elements
- }
+ plot_kinds = {_plot_kind_from_tag_name(tag_name, has_date_axis) for tag_name, _ in plot_elements}
if plot_kinds == {"scatter"}:
plot_kind = "scatter"
elif plot_kinds == {"bubble"}:
@@ -249,35 +249,25 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:
x_formula=_extract_reference_formula(series_element.find("c:xVal", namespaces=_NS)),
val_formula=_extract_reference_formula(series_element.find("c:val", namespaces=_NS)),
y_formula=_extract_reference_formula(series_element.find("c:yVal", namespaces=_NS)),
- bubble_size_formula=_extract_reference_formula(
- series_element.find("c:bubbleSize", namespaces=_NS)
- ),
+ bubble_size_formula=_extract_reference_formula(series_element.find("c:bubbleSize", namespaces=_NS)),
cached_categories=_extract_reference_cache(
series_element.find("c:cat", namespaces=_NS),
date_hint=has_date_axis,
date_1904=_chart_uses_date_1904(root),
),
- cached_x_values=_extract_reference_cache(
- series_element.find("c:xVal", namespaces=_NS)
- ),
+ cached_x_values=_extract_reference_cache(series_element.find("c:xVal", namespaces=_NS)),
cached_values=_extract_reference_cache(
_first_non_none(
series_element.find("c:val", namespaces=_NS),
series_element.find("c:yVal", namespaces=_NS),
)
),
- cached_bubble_sizes=_extract_reference_cache(
- series_element.find("c:bubbleSize", namespaces=_NS)
- ),
+ cached_bubble_sizes=_extract_reference_cache(series_element.find("c:bubbleSize", namespaces=_NS)),
)
)
return ChartSpec(
- chart_type=(
- plot_elements[0][0]
- if len(plot_elements) == 1
- else "comboChart"
- ),
+ chart_type=(plot_elements[0][0] if len(plot_elements) == 1 else "comboChart"),
plot_kind=plot_kind,
title=_extract_title_text(root.find(".//c:chart/c:title", namespaces=_NS)),
category_axis_title=category_axis_title,
@@ -345,7 +335,7 @@ def render_chart_html_from_cache(spec: ChartSpec) -> str:
return ""
-def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
+def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:
categories = []
for series in spec.series:
@@ -389,7 +379,7 @@ def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: object)
return _render_html_table(headers, columns, row_count)
-def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
+def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:
x_sequences, series_names, series_y_values = _read_scatter_axes_from_workbook(
spec,
workbook,
@@ -402,7 +392,7 @@ def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: object)
)
-def _render_bubble_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
+def _render_bubble_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:
x_sequences, series_names, series_y_values, series_sizes = _read_bubble_axes_from_workbook(
spec,
workbook,
@@ -458,7 +448,7 @@ def _render_bubble_chart_from_cache(spec: ChartSpec) -> str:
def _read_scatter_axes_from_workbook(
- spec: ChartSpec, workbook: object
+ spec: ChartSpec, workbook: Workbook
) -> tuple[list[list[float]] | None, list[str], list[list[float]]]:
x_sequences = []
series_names = []
@@ -485,7 +475,7 @@ def _read_scatter_axes_from_workbook(
def _read_bubble_axes_from_workbook(
- spec: ChartSpec, workbook: object
+ spec: ChartSpec, workbook: Workbook
) -> tuple[list[list[float]] | None, list[str], list[list[float]], list[list[float]]]:
x_sequences = []
series_names = []
@@ -514,7 +504,7 @@ def _read_bubble_axes_from_workbook(
return x_sequences, series_names, series_y_values, series_sizes
-def _read_formula_vector(workbook: object, formula: str) -> tuple[str, list[object]] | None:
+def _read_formula_vector(workbook: Workbook, formula: str) -> tuple[str, list[Any]] | None:
parsed = _parse_formula(formula)
if parsed is None:
return None
@@ -540,7 +530,7 @@ def _read_formula_vector(workbook: object, formula: str) -> tuple[str, list[obje
return sheet_name, values
-def _read_formula_scalar(workbook: object, formula: str) -> str | None:
+def _read_formula_scalar(workbook: Workbook, formula: str) -> str | None:
read_result = _read_formula_vector(workbook, formula)
if read_result is None:
return None
@@ -578,7 +568,7 @@ def _unescape_formula_sheet_name(sheet_name: str) -> str:
return sheet_name.replace("''", "'")
-def _extract_reference_formula(container: object) -> str | None:
+def _extract_reference_formula(container: etree._Element) -> str | None:
ref_element = _find_reference_element(container)
if ref_element is None:
return None
@@ -589,7 +579,7 @@ def _extract_reference_formula(container: object) -> str | None:
def _extract_reference_cache(
- container: object,
+ container: etree._Element,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -616,7 +606,7 @@ def _extract_reference_cache(
def _extract_cache_points(
- cache_element: object,
+ cache_element: etree._Element,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -649,7 +639,7 @@ def _extract_cache_points(
return [points.get(index, "") for index in range(max_index + 1)]
-def _extract_multilevel_string_cache(ref_element: object) -> list[str]:
+def _extract_multilevel_string_cache(ref_element: etree._Element) -> list[str]:
level_maps = []
max_index = -1
for level in ref_element.findall("c:multiLvlStrCache/c:lvl", namespaces=_NS):
@@ -675,16 +665,12 @@ def _extract_multilevel_string_cache(ref_element: object) -> list[str]:
rows = []
for point_index in range(max_index + 1):
- parts = [
- value_map[point_index]
- for value_map in level_maps
- if value_map.get(point_index)
- ]
+ parts = [value_map[point_index] for value_map in level_maps if value_map.get(point_index)]
rows.append(" / ".join(parts))
return rows
-def _extract_tx_formula(tx_element: object) -> str | None:
+def _extract_tx_formula(tx_element: etree._Element) -> str | None:
if tx_element is None:
return None
str_ref = tx_element.find("c:strRef", namespaces=_NS)
@@ -696,7 +682,7 @@ def _extract_tx_formula(tx_element: object) -> str | None:
return formula_element.text.strip()
-def _extract_tx_text(tx_element: object) -> str | None:
+def _extract_tx_text(tx_element: etree._Element) -> str | None:
if tx_element is None:
return None
@@ -712,14 +698,14 @@ def _extract_tx_text(tx_element: object) -> str | None:
return None
-def _extract_title_text(title_element: object) -> str:
+def _extract_title_text(title_element: etree._Element) -> str:
if title_element is None:
return ""
texts = title_element.findall(".//a:t", namespaces=_NS)
return "".join(text.text or "" for text in texts).strip()
-def _find_reference_element(container: object) -> object | None:
+def _find_reference_element(container: etree._Element) -> object | None:
if container is None:
return None
for tag_name in ("strRef", "numRef", "multiLvlStrRef"):
@@ -729,14 +715,14 @@ def _find_reference_element(container: object) -> object | None:
return None
-def _first_non_none(*values: object) -> object | None:
+def _first_non_none(*values: Any) -> object | None:
for value in values:
if value is not None:
return value
return None
-def _collect_plot_elements(plot_area: object) -> list[tuple[str, object]]:
+def _collect_plot_elements(plot_area: etree._Element) -> list[tuple[str, etree._Element]]:
plot_elements = []
for child in plot_area:
if not isinstance(child.tag, str):
@@ -757,14 +743,14 @@ def _plot_kind_from_tag_name(tag_name: str, has_date_axis: bool) -> str:
return "category"
-def _chart_uses_date_1904(root: object) -> bool:
+def _chart_uses_date_1904(root: etree._Element) -> bool:
date_1904 = root.find("c:date1904", namespaces=_NS)
if date_1904 is None:
return False
return date_1904.get("val") == "1"
-def _resolve_series_name(series: SeriesSpec, index: int, workbook: object = None) -> str:
+def _resolve_series_name(series: SeriesSpec, index: int, workbook: Workbook | None = None) -> str:
if workbook is not None and series.name_formula:
workbook_name = _read_formula_scalar(workbook, series.name_formula)
if workbook_name:
@@ -914,16 +900,13 @@ def _stringify_cache_value(
serial = float(value)
except (TypeError, ValueError):
return value
- return (
- _excel_serial_to_iso(serial, date_1904=date_1904)
- or value
- )
+ return _excel_serial_to_iso(serial, date_1904=date_1904) or value
return value
def _stringify_cell_value(
- value: object,
+ value: Any,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -941,10 +924,7 @@ def _stringify_cell_value(
return value.isoformat()
if date_hint and isinstance(value, (int, float)):
- return (
- _excel_serial_to_iso(float(value), date_1904=date_1904)
- or _stringify_non_date_value(value)
- )
+ return _excel_serial_to_iso(float(value), date_1904=date_1904) or _stringify_non_date_value(value)
return _stringify_non_date_value(value)
@@ -967,7 +947,7 @@ def _excel_serial_to_iso(serial: float, *, date_1904: bool = False) -> str | Non
return str(excel_value)
-def _stringify_non_date_value(value: object) -> str:
+def _stringify_non_date_value(value: Any) -> str:
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value)
diff --git a/mineru/backend/utils/office_image.py b/mineru/backend/utils/office_image.py
index 342b66ea..f47f8a07 100644
--- a/mineru/backend/utils/office_image.py
+++ b/mineru/backend/utils/office_image.py
@@ -52,12 +52,8 @@ def _vector_image_format_label(part_name: object | None = None, content_type: st
return "WMF/EMF"
-def _load_placeholder_font(font_size: int) -> ImageFont.ImageFont:
- for font_name in (
- "DejaVuSans.ttf",
- "Arial.ttf",
- "LiberationSans-Regular.ttf",
- ):
+def _load_placeholder_font(font_size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
+ for font_name in ("DejaVuSans.ttf", "Arial.ttf", "LiberationSans-Regular.ttf"):
try:
return ImageFont.truetype(font_name, font_size)
except OSError:
diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.py
index a63005e7..7adf88b1 100644
--- a/mineru/backend/utils/para_block_utils.py
+++ b/mineru/backend/utils/para_block_utils.py
@@ -3,7 +3,7 @@ import copy
from collections.abc import Generator
from ...types import Block, Line, PageInfo, Span
-from ...utils.enum_class import BlockType, SplitFlag
+from ...utils.enum_class import BlockType
LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")
SECTION_MERGE_BARRIER_TYPES = {
@@ -23,11 +23,6 @@ TEXT_MERGE_TRANSPARENT_TYPES = {
BlockType.CHART,
BlockType.CODE,
}
-OCR_DET_LINES_KEY = "_ocr_det_lines"
-INTERNAL_BLOCK_METADATA_KEYS = {
- OCR_DET_LINES_KEY,
- "line_avg_height",
-}
def iter_block_spans(block: Block) -> Generator[Span, None, None]:
@@ -41,14 +36,14 @@ def iter_block_spans(block: Block) -> Generator[Span, None, None]:
def build_para_blocks_from_preproc(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
- page_info["para_blocks"] = copy.deepcopy(page_info.get("preproc_blocks", []))
+ page_info.para_blocks = copy.deepcopy(page_info.preproc_blocks)
def merge_para_text_blocks(pdf_info_list: list[PageInfo], auto_merge_by_det: bool = False) -> None:
ordered_blocks: list[tuple[int, int, Block]] = []
for page_info in pdf_info_list:
- page_idx = page_info.get("page_idx")
- for order_idx, block in enumerate(page_info.get("para_blocks", [])):
+ page_idx = page_info.page_idx
+ for order_idx, block in enumerate(page_info.para_blocks):
ordered_blocks.append((page_idx, order_idx, block))
for current_index in range(len(ordered_blocks) - 1, -1, -1):
@@ -83,7 +78,7 @@ def _merge_current_text_block(
) -> None:
"""处理当前 text block 的 merge_prev 候选合并和 Hybrid det 自动合并。"""
previous_block = None
- if current_block.get("merge_prev"):
+ if current_block.merge_prev:
previous_block = _find_previous_merge_prev_text_block(
ordered_blocks,
current_index,
@@ -167,9 +162,9 @@ def can_auto_merge_text_blocks(
current_bbox_fs = _build_bbox_fs(current_block, current_metric_lines)
previous_bbox_fs = _build_bbox_fs(previous_block, previous_metric_lines)
- if abs(current_bbox_fs[0] - first_metric_line["bbox"][0]) >= first_line_height / 2:
+ if abs(current_bbox_fs[0] - first_metric_line.bbox[0]) >= first_line_height / 2:
return False
- if abs(previous_bbox_fs[2] - last_metric_line["bbox"][2]) >= last_line_height:
+ if abs(previous_bbox_fs[2] - last_metric_line.bbox[2]) >= last_line_height:
return False
first_content = _first_non_empty_content(current_lines)
@@ -196,9 +191,12 @@ def can_auto_merge_text_blocks(
def cleanup_internal_para_block_metadata(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
- for block_key in ["preproc_blocks", "para_blocks", "discarded_blocks"]:
- for block in page_info.get(block_key, []):
- _cleanup_block_internal_metadata(block)
+ for block in page_info.preproc_blocks:
+ _cleanup_block_internal_metadata(block)
+ for block in page_info.para_blocks:
+ _cleanup_block_internal_metadata(block)
+ for block in page_info.discarded_blocks:
+ _cleanup_block_internal_metadata(block)
def _find_previous_text_block(
@@ -271,7 +269,7 @@ def _is_ref_text_list_block(block: Block) -> bool:
def _resolve_auto_metric_lines(block: Block) -> list[Line]:
"""优先使用 OCR det 行提示;没有提示时退回 block 自身 lines。"""
- return block.get(OCR_DET_LINES_KEY) or block.lines
+ return block._ocr_det_lines or block.lines
def _resolve_local_metric_lines(block: Block) -> list[Line]:
@@ -284,42 +282,42 @@ def _resolve_local_metric_lines(block: Block) -> list[Line]:
def _merge_text_block(current_block: Block, previous_block: Block, is_cross_page: bool) -> None:
if is_cross_page:
_mark_lines_cross_page(current_block.lines)
- _mark_lines_cross_page(current_block.get(OCR_DET_LINES_KEY, []))
+ _mark_lines_cross_page(current_block._ocr_det_lines)
+
+ previous_block.lines.extend(current_block.lines)
+ previous_block._ocr_det_lines.extend(current_block._ocr_det_lines)
- previous_block.setdefault("lines", []).extend(current_block.lines)
- if current_block.get(OCR_DET_LINES_KEY):
- previous_block.setdefault(OCR_DET_LINES_KEY, []).extend(current_block.get(OCR_DET_LINES_KEY, []))
- current_block["lines"] = []
- current_block[OCR_DET_LINES_KEY] = []
- current_block[SplitFlag.LINES_DELETED] = True
+ current_block.lines = []
+ current_block._ocr_det_lines = []
+ current_block._lines_deleted = True
def _mark_lines_cross_page(lines: list[Line]) -> None:
"""给跨页合并进来的文本行和 det hint 行同步打跨页标记。"""
for line in lines:
for span in line.spans:
- span[SplitFlag.CROSS_PAGE] = True
+ span._cross_page = True
def _is_cross_page_line(line: Line) -> bool:
"""判断整行是否来自跨页追加,供几何度量时排除。"""
spans = line.spans
- return bool(spans) and all(span.get(SplitFlag.CROSS_PAGE) for span in spans)
+ return bool(spans) and all(span._cross_page for span in spans)
def _merge_ref_text_list_block(current_block: Block, previous_block: Block, is_cross_page: bool) -> None:
"""合并相邻 ref_text list,并在跨页时给当前 list 内 span 标记跨页。"""
if is_cross_page:
for span in iter_block_spans(current_block):
- span[SplitFlag.CROSS_PAGE] = True
+ span._cross_page = True
- previous_block.setdefault("blocks", []).extend(current_block.blocks)
- current_block["blocks"] = []
- current_block[SplitFlag.LINES_DELETED] = True
+ previous_block.blocks.extend(current_block.blocks)
+ current_block.blocks = []
+ current_block._lines_deleted = True
def _line_height(line: Line) -> float:
- bbox = line.get("bbox")
+ bbox = line.bbox
if not bbox:
return 0
return bbox[3] - bbox[1]
@@ -328,23 +326,23 @@ def _line_height(line: Line) -> float:
def _build_bbox_fs(block: Block, lines: list[Line]) -> list[float]:
if lines:
return [
- min(line["bbox"][0] for line in lines),
- min(line["bbox"][1] for line in lines),
- max(line["bbox"][2] for line in lines),
- max(line["bbox"][3] for line in lines),
+ min(line.bbox[0] for line in lines),
+ min(line.bbox[1] for line in lines),
+ max(line.bbox[2] for line in lines),
+ max(line.bbox[3] for line in lines),
]
- return list(block.get("bbox", []))
+ return list(block.bbox or [])
def _block_has_lines(block: Block) -> bool:
- return any(line.get("spans") for line in block.lines)
+ return any(line.spans for line in block.lines)
def _first_non_empty_content(lines: list[Line]) -> str:
"""从行列表中提取第一个非空 span 文本,用于段落起始字符规则判断。"""
for line in lines:
for span in line.spans:
- content = span.get("content", "")
+ content = span.content or ""
if content:
return content
return ""
@@ -354,7 +352,7 @@ def _last_non_empty_content(lines: list[Line]) -> str:
"""从行列表中提取最后一个非空 span 文本,用于段落结尾字符规则判断。"""
for line in reversed(lines):
for span in reversed(line.spans):
- content = span.get("content", "")
+ content = span.content or ""
if content:
return content
return ""
@@ -362,12 +360,12 @@ def _last_non_empty_content(lines: list[Line]) -> str:
def _has_mergeable_block_bbox_relation(current_block: Block, previous_block: Block) -> bool:
"""复刻 pipeline text 合并的核心几何条件:当前块上边界进入前块范围。"""
- return current_block["bbox"][1] < previous_block["bbox"][3]
+ return current_block.bbox[1] < previous_block.bbox[3]
def _cleanup_block_internal_metadata(block: Block) -> None:
"""递归清理只供 finalize 内部流程使用的临时字段。"""
- for metadata_key in INTERNAL_BLOCK_METADATA_KEYS:
- block.pop(metadata_key, None)
+ block._ocr_det_lines = []
+ block._line_avg_height = 0
for sub_block in block.blocks:
_cleanup_block_internal_metadata(sub_block)
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index 4f30ae00..bc4a2afa 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -9,7 +9,7 @@ import os
import threading
import time
from contextlib import asynccontextmanager, contextmanager
-from typing import Any, Generator, Iterator
+from typing import Any, AsyncIterator, Generator, Iterator
import pypdfium2 as pdfium
from loguru import logger
@@ -386,17 +386,14 @@ def _predictor_uses_mlx(predictor: MinerUClient, backend: str | None = None) ->
return type(client).__module__.endswith(".mlx_client")
-def _maybe_enable_serial_execution(
- predictor: MinerUClient,
- backend: str | None = None,
-) -> MinerUClient:
+def _maybe_enable_serial_execution(predictor: MinerUClient, backend: str | None = None) -> MinerUClient:
if _predictor_uses_mlx(predictor, backend) and not hasattr(predictor, "_mineru_execution_lock"):
- predictor._mineru_execution_lock = threading.Lock()
+ setattr(predictor, "_mineru_execution_lock", threading.Lock())
return predictor
@contextmanager
-def predictor_execution_guard(predictor: MinerUClient) -> None:
+def predictor_execution_guard(predictor: MinerUClient) -> Iterator[None]:
lock = getattr(predictor, "_mineru_execution_lock", None)
if lock is None:
yield
@@ -406,7 +403,7 @@ def predictor_execution_guard(predictor: MinerUClient) -> None:
@asynccontextmanager
-async def aio_predictor_execution_guard(predictor: MinerUClient) -> None:
+async def aio_predictor_execution_guard(predictor: MinerUClient) -> AsyncIterator[None]:
lock = getattr(predictor, "_mineru_execution_lock", None)
if lock is None:
yield
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index 85523855..0fb648f6 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -27,7 +27,7 @@ def _copy_raw_text_block_metadata(raw_block_type: str, block_info: ContentBlock,
if raw_block_type != BlockType.TEXT:
return
if "merge_prev" in block_info:
- block["merge_prev"] = block_info["merge_prev"]
+ block.merge_prev = block_info["merge_prev"]
class MagicModel:
@@ -211,9 +211,7 @@ class MagicModel:
else:
line = Line(spans=spans, bbox=block_bbox)
- block = Block(type=block_type, bbox=block_bbox, lines=[line])
- block["angle"] = block_angle
- block["index"] = index
+ block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)
if block_sub_type:
block["sub_type"] = block_sub_type
if raw_block_type == "table" and "cell_merge" in content_block:
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index 9a977004..9f459809 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -66,16 +66,16 @@ def _normalize_text_content(content: str | None) -> str:
def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int) -> bool:
"""判断当前 span 后面是否还有可拼接文本,避免把分隔空格落到段落末尾。"""
- for next_line_idx in range(line_idx, len(para_block["lines"])):
- next_line = para_block["lines"][next_line_idx]
+ for next_line_idx in range(line_idx, len(para_block.lines)):
+ next_line = para_block.lines[next_line_idx]
start_span_idx = span_idx + 1 if next_line_idx == line_idx else 0
- for next_span in next_line.get("spans", [])[start_span_idx:]:
- next_span_type = next_span.get("type")
+ for next_span in next_line.spans[start_span_idx:]:
+ next_span_type = next_span.type
if next_span_type == ContentType.TEXT:
- if _normalize_text_content(next_span.get("content")).strip():
+ if _normalize_text_content(next_span.content).strip():
return True
elif next_span_type == ContentType.INLINE_EQUATION:
- if str(next_span.get("content", "")).strip():
+ if str(next_span.content).strip():
return True
return False
@@ -167,7 +167,7 @@ def _render_visual_block_segments(
rendered_segments = []
for line in block.lines:
for span in line.spans:
- if span.get("type") != ContentType.IMAGE:
+ if span.type != ContentType.IMAGE:
continue
rendered_segments.extend(
_build_visual_body_segments(
@@ -184,7 +184,7 @@ def _render_visual_block_segments(
rendered_segments = []
for line in block.lines:
for span in line.spans:
- if span.get("type") != ContentType.CHART:
+ if span.type != ContentType.CHART:
continue
rendered_segments.extend(
_build_visual_body_segments(
@@ -201,7 +201,7 @@ def _render_visual_block_segments(
rendered_segments = []
for line in block.lines:
for span in line.spans:
- if span.get("type") != ContentType.TABLE:
+ if span.type != ContentType.TABLE:
continue
if table_enable and span.get("html", ""):
rendered_segments.append(
@@ -273,9 +273,9 @@ def merge_para_with_text(
escape_markdown_text = para_block.type != BlockType.CODE_BODY
para_text = ""
- for i, line in enumerate(para_block["lines"]):
- for j, span in enumerate(line["spans"]):
- span_type = span["type"]
+ for i, line in enumerate(para_block.lines):
+ for j, span in enumerate(line.spans):
+ span_type = span.type
content = ""
if span_type == ContentType.TEXT:
content = span["content"]
@@ -301,7 +301,7 @@ def merge_para_with_text(
# logger.info(f'block_lang: {block_lang}, content: {content}')
# 判断是否为行末span
- is_last_span = j == len(line["spans"]) - 1
+ is_last_span = j == len(line.spans) - 1
has_following_joinable_span = _has_following_joinable_span(para_block, i, j)
if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
@@ -316,11 +316,11 @@ def merge_para_with_text(
if is_last_span and span_type == ContentType.TEXT and is_hyphen_at_line_end(content):
# 如果下一行的第一个span是小写字母开头,删除连字符
if (
- i + 1 < len(para_block["lines"])
- and para_block["lines"][i + 1].get("spans")
- and para_block["lines"][i + 1]["spans"][0].get("type") == ContentType.TEXT
- and para_block["lines"][i + 1]["spans"][0].get("content", "")
- and para_block["lines"][i + 1]["spans"][0]["content"][0].islower()
+ i + 1 < len(para_block.lines)
+ and para_block.lines[i + 1].get("spans")
+ and para_block.lines[i + 1]["spans"][0].get("type") == ContentType.TEXT
+ and para_block.lines[i + 1]["spans"][0].get("content", "")
+ and para_block.lines[i + 1]["spans"][0]["content"][0].islower()
):
para_text += content[:-1]
else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
@@ -423,7 +423,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
"sub_type": para_block.get("sub_type", ""),
"list_items": [],
}
- for block in para_block["blocks"]:
+ for block in para_block.blocks:
item_text = merge_para_with_text(block, escape_text_block_prefix=False)
if item_text.strip():
para_content["list_items"].append(item_text)
@@ -447,18 +447,18 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
para_content["img_path"] = _build_media_path(img_buket_path, image_path)
para_content["content"] = image_content if image_content else ""
_apply_visual_sub_type(para_content, para_block)
- for block in para_block["blocks"]:
- if block["type"] == BlockType.IMAGE_CAPTION:
+ for block in para_block.blocks:
+ if block.type == BlockType.IMAGE_CAPTION:
para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.IMAGE_FOOTNOTE:
+ if block.type == BlockType.IMAGE_FOOTNOTE:
para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.TABLE:
para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
- for block in para_block["blocks"]:
- if block["type"] == BlockType.TABLE_BODY:
- for line in block["lines"]:
- for span in line["spans"]:
- if span["type"] == ContentType.TABLE:
+ for block in para_block.blocks:
+ if block.type == BlockType.TABLE_BODY:
+ for line in block.lines:
+ for span in line.spans:
+ if span.type == ContentType.TABLE:
if span.get("html", ""):
para_content[BlockType.TABLE_BODY] = _format_embedded_html(
span["html"],
@@ -468,9 +468,9 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
if span.get("image_path", ""):
para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
- if block["type"] == BlockType.TABLE_CAPTION:
+ if block.type == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
- if block["type"] == BlockType.TABLE_FOOTNOTE:
+ if block.type == BlockType.TABLE_FOOTNOTE:
para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.CHART:
image_path, chart_content = get_body_data(para_block)
@@ -489,14 +489,14 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
para_content[BlockType.CHART_FOOTNOTE].append(merge_para_with_text(block))
elif para_type == BlockType.CODE:
para_content = {"type": BlockType.CODE, "sub_type": para_block["sub_type"], BlockType.CODE_CAPTION: []}
- for block in para_block["blocks"]:
- if block["type"] == BlockType.CODE_BODY:
+ for block in para_block.blocks:
+ if block.type == BlockType.CODE_BODY:
code_text = merge_para_with_text(block)
if para_block["sub_type"] == BlockType.CODE:
guess_lang = para_block.get("guess_lang", "txt")
code_text = f"```{guess_lang}\n{code_text}\n```"
para_content[BlockType.CODE_BODY] = code_text
- if block["type"] == BlockType.CODE_CAPTION:
+ if block.type == BlockType.CODE_CAPTION:
para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
page_width, page_height = page_size
@@ -516,7 +516,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> dict:
- para_type = para_block["type"]
+ para_type = para_block.type
para_content = {}
if para_type in [
BlockType.HEADER,
@@ -581,10 +581,10 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
image_source = {
"path": _build_media_path(img_buket_path, image_path),
}
- for block in para_block["blocks"]:
- if block["type"] == BlockType.IMAGE_CAPTION:
+ for block in para_block.blocks:
+ if block.type == BlockType.IMAGE_CAPTION:
image_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.IMAGE_FOOTNOTE:
+ if block.type == BlockType.IMAGE_FOOTNOTE:
image_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.IMAGE,
@@ -613,10 +613,10 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
else:
table_type = ContentTypeV2.TABLE_SIMPLE
- for block in para_block["blocks"]:
- if block["type"] == BlockType.TABLE_CAPTION:
+ for block in para_block.blocks:
+ if block.type == BlockType.TABLE_CAPTION:
table_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.TABLE_FOOTNOTE:
+ if block.type == BlockType.TABLE_FOOTNOTE:
table_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.TABLE,
@@ -633,10 +633,10 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
chart_caption = []
chart_footnote = []
image_path, chart_content = get_body_data(para_block)
- for block in para_block["blocks"]:
- if block["type"] == BlockType.CHART_CAPTION:
+ for block in para_block.blocks:
+ if block.type == BlockType.CHART_CAPTION:
chart_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.CHART_FOOTNOTE:
+ if block.type == BlockType.CHART_FOOTNOTE:
chart_footnote.extend(merge_para_with_text_v2(block))
para_content = {
"type": ContentTypeV2.CHART,
@@ -653,10 +653,10 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
elif para_type == BlockType.CODE:
code_caption = []
code_content = []
- for block in para_block["blocks"]:
- if block["type"] == BlockType.CODE_CAPTION:
+ for block in para_block.blocks:
+ if block.type == BlockType.CODE_CAPTION:
code_caption.extend(merge_para_with_text_v2(block))
- if block["type"] == BlockType.CODE_BODY:
+ if block.type == BlockType.CODE_BODY:
code_content = merge_para_with_text_v2(block)
sub_type = para_block["sub_type"]
if sub_type == BlockType.CODE:
@@ -702,7 +702,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
else:
list_type = ContentTypeV2.LIST_TEXT
list_items = []
- for block in para_block["blocks"]:
+ for block in para_block.blocks:
item_content = merge_para_with_text_v2(block)
if item_content:
list_items.append(
@@ -747,7 +747,7 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
for line in lines:
for span in line.spans:
- span_type = span.get("type")
+ span_type = span.type
if span_type == ContentType.TABLE:
return span.get("image_path", ""), span.get("html", "")
elif span_type == ContentType.CHART:
@@ -776,18 +776,18 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
def merge_para_with_text_v2(para_block: Block) -> str:
block_text = ""
- for line in para_block["lines"]:
- for span in line["spans"]:
- if span["type"] in [ContentType.TEXT]:
- span["content"] = _normalize_text_content(span.get("content"))
+ for line in para_block.lines:
+ for span in line.spans:
+ if span.type in [ContentType.TEXT]:
+ span["content"] = _normalize_text_content(span.content)
block_text += span["content"]
block_lang = detect_lang(block_text)
para_content = []
- para_type = para_block["type"]
- for i, line in enumerate(para_block["lines"]):
- for j, span in enumerate(line["spans"]):
- span_type = span["type"]
+ para_type = para_block.type
+ for i, line in enumerate(para_block.lines):
+ for j, span in enumerate(line.spans):
+ span_type = span.type
if span.get("content", "").strip():
if span_type == ContentType.TEXT:
if para_type == BlockType.PHONETIC:
@@ -804,7 +804,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
# logger.info(f'block_lang: {block_lang}, content: {content}')
# 判断是否为行末span
- is_last_span = j == len(line["spans"]) - 1
+ is_last_span = j == len(line.spans) - 1
has_following_joinable_span = _has_following_joinable_span(para_block, i, j)
if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
@@ -817,11 +817,11 @@ def merge_para_with_text_v2(para_block: Block) -> str:
if is_last_span and is_hyphen_at_line_end(span["content"]):
# 如果下一行的第一个span是小写字母开头,删除连字符
if (
- i + 1 < len(para_block["lines"])
- and para_block["lines"][i + 1].get("spans")
- and para_block["lines"][i + 1]["spans"][0].get("type") == ContentType.TEXT
- and para_block["lines"][i + 1]["spans"][0].get("content", "")
- and para_block["lines"][i + 1]["spans"][0]["content"][0].islower()
+ i + 1 < len(para_block.lines)
+ and para_block.lines[i + 1].get("spans")
+ and para_block.lines[i + 1]["spans"][0].get("type") == ContentType.TEXT
+ and para_block.lines[i + 1]["spans"][0].get("content", "")
+ and para_block.lines[i + 1]["spans"][0]["content"][0].islower()
):
span_content = span["content"][:-1]
else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
@@ -862,7 +862,6 @@ def union_make(
make_mode: str,
img_buket_path: str = "",
) -> str | list:
-
formula_enable = get_formula_enable(os.getenv("MINERU_VLM_FORMULA_ENABLE", "True").lower() == "true")
table_enable = get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
diff --git a/mineru/types.py b/mineru/types.py
index 08e71c0f..5b621152 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -220,7 +220,6 @@ BLOCK_TYPES = {
# BlockType.DOC_TITLE,
# BlockType.PARAGRAPH_TITLE,
# ]
-# OCR_DET_LINES_KEY = "_ocr_det_lines"
# OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {
# BlockType.LIST,
# BlockType.INDEX,
@@ -366,12 +365,15 @@ def _install_dict_compat(*classes) -> None:
# ── model types ─────────────────────────────────────────────────────
+EMPTY_BBOX = (0.0, 0.0, 0.0, 0.0)
+
+
@dataclass
class Span:
"""Leaf node of the block tree. Holds text, formula, image, or table content."""
type: str
- bbox: tuple[float, float, float, float] | None = None
+ bbox: tuple[float, float, float, float]
content: str = ""
score: float = 0.0
image_path: str = ""
@@ -380,12 +382,14 @@ class Span:
latex: str = ""
_extra: dict = field(default_factory=dict)
+ # Internal
+ _cross_page: bool = False
+
@classmethod
def from_dict(cls, d: dict) -> Span:
- bbox = d.get("bbox")
return cls(
type=d["type"],
- bbox=tuple(bbox) if bbox else None,
+ bbox=tuple(d["bbox"]),
content=d.get("content", ""),
score=d.get("score", 0.0),
image_path=d.get("image_path", ""),
@@ -399,47 +403,67 @@ class Span:
class Line:
"""A line within a block, containing one or more spans."""
+ bbox: tuple[float, float, float, float]
spans: list[Span] = field(default_factory=list)
- bbox: tuple[float, float, float, float] | None = None
_extra: dict = field(default_factory=dict)
+ # Internal
+ _is_list_start: bool = False
+ _is_list_end: bool = False
+
@classmethod
def from_dict(cls, d: dict) -> Line:
- return cls(spans=[Span.from_dict(s) for s in d.get("spans", [])])
+ return cls(
+ bbox=tuple(d["bbox"]),
+ spans=[Span.from_dict(s) for s in d.get("spans", [])],
+ )
@dataclass
class Block:
"""A layout block on a page. May nest child blocks (e.g. list items, image body)."""
+ # Required
+ index: int
type: str
- bbox: tuple[float, float, float, float] | None = None
+ bbox: tuple[float, float, float, float]
lines: list[Line] = field(default_factory=list)
blocks: list[Block] = field(default_factory=list)
+
+ # Optional
+ angle: int | None = None
+ score: float | None = None
level: int | None = None
- section_number: str = ""
sub_type: str = ""
- html: str = ""
- merge_prev: bool = False
- index: int | None = None
guess_lang: str = ""
+ merge_prev: bool = False
+ section_number: str = ""
+ html: str = ""
+
+ # Internal
+ _cross_page: bool = False
+ _lines_deleted: bool = False
+ _ocr_det_lines: list[Line] = field(default_factory=list)
+ _line_avg_height: int = 0
+
_extra: dict = field(default_factory=dict)
@classmethod
def from_dict(cls, d: dict) -> Block:
- bbox = d.get("bbox")
return cls(
+ index=d["index"],
type=d["type"],
- bbox=tuple(bbox) if bbox else None,
+ bbox=tuple(d["bbox"]),
lines=[Line.from_dict(line) for line in d.get("lines", [])],
blocks=[Block.from_dict(b) for b in d.get("blocks", [])],
+ angle=d.get("angle"),
+ score=d.get("score"),
level=d.get("level"),
- section_number=d.get("section_number", ""),
sub_type=d.get("sub_type", ""),
- html=d.get("html", ""),
- merge_prev=d.get("merge_prev", False),
- index=d.get("index"),
guess_lang=d.get("guess_lang", ""),
+ merge_prev=d.get("merge_prev", False),
+ section_number=d.get("section_number", ""),
+ html=d.get("html", ""),
)
def all_spans(self) -> Iterator[Span]:
diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.py
index b5063706..00247b97 100644
--- a/mineru/utils/draw_bbox.py
+++ b/mineru/utils/draw_bbox.py
@@ -3,12 +3,11 @@ import json
from io import BytesIO
from loguru import logger
-from pypdf import PdfReader, PdfWriter, PageObject
+from pypdf import PageObject, PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from .enum_class import BlockType, ContentType, SplitFlag
-
# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。
TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {
BlockType.TEXT,
@@ -46,25 +45,25 @@ def cal_canvas_rect(page, bbox):
rect: [x0, y0, width, height] representing the rectangle coordinates on the canvas.
"""
page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
-
- actual_width = page_width # The width of the final PDF display
+
+ actual_width = page_width # The width of the final PDF display
actual_height = page_height # The height of the final PDF display
-
+
rotation_obj = page.get("/Rotate", 0)
try:
rotation = int(rotation_obj) % 360 # cast rotation to int to handle IndirectObject
except (ValueError, TypeError) as e:
logger.warning(f"Invalid /Rotate value {rotation_obj!r} on page; defaulting to 0. Error: {e}")
rotation = 0
-
+
if rotation in [90, 270]:
# PDF is rotated 90 degrees or 270 degrees, and the width and height need to be swapped
actual_width, actual_height = actual_height, actual_width
-
+
x0, y0, x1, y1 = bbox
rect_w = abs(x1 - x0)
rect_h = abs(y1 - y0)
-
+
if rotation == 270:
rect_w, rect_h = rect_h, rect_w
x0 = actual_height - y1
@@ -74,12 +73,12 @@ def cal_canvas_rect(page, bbox):
# y0 stays the same
elif rotation == 90:
rect_w, rect_h = rect_h, rect_w
- x0, y0 = y0, x0
+ x0, y0 = y0, x0
else:
# rotation == 0
y0 = page_height - y1
-
- rect = [x0, y0, rect_w, rect_h]
+
+ rect = [x0, y0, rect_w, rect_h]
return rect
@@ -88,7 +87,7 @@ def draw_bbox_without_number(i, bbox_list, page, c, rgb_config, fill_config):
page_data = bbox_list[i]
for bbox in page_data:
- rect = cal_canvas_rect(page, bbox) # Define the rectangle
+ rect = cal_canvas_rect(page, bbox) # Define the rectangle
if fill_config: # filled rectangle
c.setFillColorRGB(new_rgb[0], new_rgb[1], new_rgb[2], 0.3)
@@ -107,8 +106,8 @@ def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_b
for j, bbox in enumerate(page_data):
# 确保bbox的每个元素都是float
- rect = cal_canvas_rect(page, bbox) # Define the rectangle
-
+ rect = cal_canvas_rect(page, bbox) # Define the rectangle
+
if draw_bbox:
if fill_config:
c.setFillColorRGB(*new_rgb, 0.3)
@@ -118,7 +117,7 @@ def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_b
c.rect(rect[0], rect[1], rect[2], rect[3], stroke=1, fill=0)
c.setFillColorRGB(*new_rgb, 1.0)
c.setFontSize(size=10)
-
+
c.saveState()
rotation_obj = page.get("/Rotate", 0)
try:
@@ -135,7 +134,7 @@ def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_b
c.translate(rect[0] - 2, rect[1] + 10)
elif rotation == 270:
c.translate(rect[0] + rect[2] - 10, rect[1] - 2)
-
+
c.rotate(rotation)
c.drawString(0, 0, str(j + 1))
c.restoreState()
@@ -167,8 +166,8 @@ def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
list_items = []
indices = []
- for dropped_bbox in page['discarded_blocks']:
- page_dropped_list.append(dropped_bbox['bbox'])
+ for dropped_bbox in page["discarded_blocks"]:
+ page_dropped_list.append(dropped_bbox["bbox"])
dropped_bbox_list.append(page_dropped_list)
for block in _get_layout_source_blocks(page):
bbox = block["bbox"]
@@ -323,16 +322,16 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
dropped_list = []
def get_span_info(span):
- if span['type'] == ContentType.TEXT:
- page_text_list.append(span['bbox'])
- elif span['type'] == ContentType.INLINE_EQUATION:
- page_inline_equation_list.append(span['bbox'])
- elif span['type'] == ContentType.INTERLINE_EQUATION:
- page_interline_equation_list.append(span['bbox'])
- elif span['type'] in [ContentType.IMAGE, ContentType.CHART]:
- page_image_list.append(span['bbox'])
- elif span['type'] == ContentType.TABLE:
- page_table_list.append(span['bbox'])
+ if span["type"] == ContentType.TEXT:
+ page_text_list.append(span["bbox"])
+ elif span["type"] == ContentType.INLINE_EQUATION:
+ page_inline_equation_list.append(span["bbox"])
+ elif span["type"] == ContentType.INTERLINE_EQUATION:
+ page_interline_equation_list.append(span["bbox"])
+ elif span["type"] in [ContentType.IMAGE, ContentType.CHART]:
+ page_image_list.append(span["bbox"])
+ elif span["type"] == ContentType.TABLE:
+ page_table_list.append(span["bbox"])
for page in pdf_info:
page_text_list = []
@@ -342,24 +341,23 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
page_table_list = []
page_dropped_list = []
-
# 构造dropped_list
- for block in page['discarded_blocks']:
- for line in block['lines']:
- for span in line['spans']:
- page_dropped_list.append(span['bbox'])
+ for block in page["discarded_blocks"]:
+ for line in block["lines"]:
+ for span in line["spans"]:
+ page_dropped_list.append(span["bbox"])
dropped_list.append(page_dropped_list)
# 构造其余useful_list
# for block in page['para_blocks']: # span直接用分段合并前的结果就可以
- for block in page['preproc_blocks']:
- if block['type'] in SPAN_SOURCE_BLOCK_TYPES:
- for line in block['lines']:
- for span in line['spans']:
+ for block in page["preproc_blocks"]:
+ if block["type"] in SPAN_SOURCE_BLOCK_TYPES:
+ for line in block["lines"]:
+ for span in line["spans"]:
get_span_info(span)
- elif block['type'] in [BlockType.IMAGE, BlockType.TABLE, BlockType.CHART, BlockType.CODE]:
- for sub_block in block['blocks']:
- for line in sub_block['lines']:
- for span in line['spans']:
+ elif block["type"] in [BlockType.IMAGE, BlockType.TABLE, BlockType.CHART, BlockType.CODE]:
+ for sub_block in block["blocks"]:
+ for line in sub_block["lines"]:
+ for span in line["spans"]:
get_span_info(span)
text_list.append(page_text_list)
inline_equation_list.append(page_inline_equation_list)
@@ -381,7 +379,7 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
c = canvas.Canvas(packet, pagesize=custom_page_size)
# 获取当前页面的数据
- draw_bbox_without_number(i, text_list, page, c,[255, 0, 0], False)
+ draw_bbox_without_number(i, text_list, page, c, [255, 0, 0], False)
draw_bbox_without_number(i, inline_equation_list, page, c, [0, 255, 0], False)
draw_bbox_without_number(i, interline_equation_list, page, c, [0, 0, 255], False)
draw_bbox_without_number(i, image_list, page, c, [255, 204, 0], False)
@@ -423,5 +421,6 @@ if __name__ == "__main__":
pdf_ann = json.load(f)
pdf_info = pdf_ann["pdf_info"]
from mineru.utils.pdf_document import PDFDocument
+
doc = PDFDocument(pdf_bytes)
doc.draw_layout_bbox(pdf_info, "examples/output_with_layout.pdf")
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index de013d9c..8ffa934a 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -5,6 +5,8 @@ import multiprocessing
import os
import threading
import time
+from concurrent.futures import ALL_COMPLETED, ProcessPoolExecutor, wait
+from concurrent.futures.process import BrokenProcessPool
from io import BytesIO
import numpy as np
@@ -13,13 +15,13 @@ from loguru import logger
from PIL import Image, ImageOps
from mineru.data.data_reader_writer import FileBasedDataWriter
-from mineru.utils.check_sys_env import is_windows_environment
from mineru.utils.bbox_utils import normalize_to_int_bbox
-from mineru.utils.os_env_config import get_load_images_timeout, get_load_images_threads
-from mineru.utils.pdf_reader import image_to_b64str, image_to_bytes, page_to_image
+from mineru.utils.check_sys_env import is_windows_environment
from mineru.utils.enum_class import ImageType
from mineru.utils.hash_utils import str_sha256
+from mineru.utils.os_env_config import get_load_images_threads, get_load_images_timeout
from mineru.utils.pdf_page_id import get_end_page_id
+from mineru.utils.pdf_reader import image_to_b64str, image_to_bytes, page_to_image
from mineru.utils.pdfium_guard import (
close_pdfium_child,
close_pdfium_document,
@@ -28,10 +30,6 @@ from mineru.utils.pdfium_guard import (
pdfium_guard,
)
-from concurrent.futures import ProcessPoolExecutor, wait, ALL_COMPLETED
-from concurrent.futures.process import BrokenProcessPool
-
-
DEFAULT_PDF_IMAGE_DPI = 200
# DEFAULT_PDF_IMAGE_DPI = 144
MAX_PDF_RENDER_PROCESSES = 3
@@ -77,13 +75,9 @@ def pdf_page_to_image(
return image_dict
-def _load_images_from_pdf_worker(
- pdf_bytes, dpi, start_page_id, end_page_id, image_type
-):
+def _load_images_from_pdf_worker(pdf_bytes, dpi, start_page_id, end_page_id, image_type):
"""用于进程池的包装函数"""
- return load_images_from_pdf_core(
- pdf_bytes, dpi, start_page_id, end_page_id, image_type
- )
+ return load_images_from_pdf_core(pdf_bytes, dpi, start_page_id, end_page_id, image_type)
def _close_image_dicts(images_list) -> None:
@@ -137,9 +131,7 @@ def _get_render_process_plan(
) -> tuple[int, list[tuple[int, int]]]:
total_pages = end_page_id - start_page_id + 1
actual_threads = _calculate_render_process_count(total_pages, threads, cpu_count)
- return actual_threads, _build_render_page_ranges(
- start_page_id, end_page_id, actual_threads
- )
+ return actual_threads, _build_render_page_ranges(start_page_id, end_page_id, actual_threads)
def _get_pdf_render_pool_capacity(cpu_count=None) -> int:
@@ -158,10 +150,7 @@ def _create_pdf_render_executor(max_workers: int) -> ProcessPoolExecutor:
start_method = multiprocessing.get_start_method()
if start_method != "spawn":
- logger.debug(
- "PDF image rendering switches multiprocessing start method "
- f"from {start_method} to spawn"
- )
+ logger.debug(f"PDF image rendering switches multiprocessing start method from {start_method} to spawn")
return ProcessPoolExecutor(
max_workers=max_workers,
mp_context=multiprocessing.get_context("spawn"),
@@ -215,9 +204,7 @@ def _get_pdf_render_executor() -> ProcessPoolExecutor:
if _pdf_render_executor is None:
max_workers = _get_pdf_render_pool_capacity()
_pdf_render_executor = _create_pdf_render_executor(max_workers=max_workers)
- logger.debug(
- f"Created persistent PDF render executor with max_workers={max_workers}"
- )
+ logger.debug(f"Created persistent PDF render executor with max_workers={max_workers}")
return _pdf_render_executor
@@ -287,8 +274,7 @@ def _load_images_from_pdf_bytes_range(
)
logger.debug(
- f"PDF image rendering uses {actual_threads} processes for pages "
- f"{start_page_id + 1}-{end_page_id + 1}: {page_ranges}"
+ f"PDF image rendering uses {actual_threads} processes for pages {start_page_id + 1}-{end_page_id + 1}: {page_ranges}"
)
executor = _get_pdf_render_executor()
@@ -313,10 +299,7 @@ def _load_images_from_pdf_bytes_range(
_, not_done = wait(futures, timeout=timeout, return_when=ALL_COMPLETED)
if not_done:
recycle_executor = True
- raise TimeoutError(
- f"PDF image rendering timeout after {timeout}s "
- f"for pages {start_page_id + 1}-{end_page_id + 1}"
- )
+ raise TimeoutError(f"PDF image rendering timeout after {timeout}s for pages {start_page_id + 1}-{end_page_id + 1}")
all_results = []
for future in futures:
@@ -514,14 +497,14 @@ def cut_image(
return img_hash256_path
-def get_crop_img(bbox: tuple, pil_img, scale=2):
+def get_crop_img(bbox: tuple[float, float, float, float], pil_img: Image.Image, scale: float = 2.0):
scale_bbox = normalize_to_int_bbox([float(v) * scale for v in bbox])
if scale_bbox is None:
return pil_img.crop((0, 0, 0, 0))
return pil_img.crop(tuple(scale_bbox))
-def get_crop_np_img(bbox: tuple, input_img, scale=2):
+def get_crop_np_img(bbox: tuple, input_img, scale: float = 2.0):
if isinstance(input_img, Image.Image):
np_img = np.asarray(input_img)
elif isinstance(input_img, np.ndarray):
diff --git a/pyproject.toml b/pyproject.toml
index b8b05b91..a6d4ae9f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -60,6 +60,7 @@ dependencies = [
"fastapi",
"python-multipart",
"uvicorn",
+ "lxml-stubs",
]
[project.optional-dependencies]