Skip to content

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

refactor: convert dict[str, Any] to dataclass types (PageInfo/Block/Span) in backend utils and mineru/utils

jinzhenj4a28d0f46efa
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index babf7b56..705e2f91 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -284,7 +284,7 @@ def _formula_item_to_pixel_bbox(item: dict[str, Any]) -> list[int] | None:
return None
-def _build_inline_formula_inputs(images_layout_res: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
+def _build_inline_formula_inputs(images_layout_res: list[list[dict[str, Any]]]) -> list[list[dict[str, Any]]]:
inline_formula_inputs = []
for layout_res in images_layout_res:
page_inline_formula_inputs = []
@@ -330,7 +330,7 @@ def _normalize_page_size(page_image: Any) -> list[int]:
return width, height
-def _bbox_to_pixel_bbox(bbox: list[float], page_size: list[int]) -> list[int]:
+def _bbox_to_pixel_bbox(bbox: list[float], page_size: list[int]) -> list[int] | None:
"""将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""
if bbox is None or len(bbox) != 4:
return None
@@ -396,7 +396,7 @@ def _predict_layout_for_title_split(
hybrid_pipeline_model: MineruHybridModel,
images: list[Image.Image],
batch_ratio: int,
-) -> list[dict[str, Any]]:
+) -> list[list[dict[str, Any]]]:
"""执行layout小模型检测,专门为Hybrid标题拆分提供页面layout结果。"""
return run_layout_inference(
hybrid_pipeline_model.layout_model.batch_predict,
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index fd199130..ce4e8a9a 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -132,13 +132,13 @@ def _normalize_split_title_blocks(pdf_info_list: list[PageInfo]) -> None:
BlockType.PARAGRAPH_TITLE: 2,
}
for page_info in pdf_info_list:
- for block_key in ["preproc_blocks", "para_blocks"]:
- for block in page_info.get(block_key, []):
- title_level = title_type_to_level.get(block.get("type"))
+ for blocks in [page_info.preproc_blocks, page_info.para_blocks]:
+ for block in blocks:
+ title_level = title_type_to_level.get(block.type)
if title_level is None:
continue
- block["type"] = BlockType.TITLE
- block["level"] = title_level
+ block.type = BlockType.TITLE
+ block.level = title_level
def init_middle_json(_ocr_enable: bool, _vlm_ocr_enable: bool) -> dict[str, Any]:
@@ -165,10 +165,7 @@ def apply_server_side_postprocess(
def finalize_middle_json_from_preproc(pdf_info_list: list[PageInfo]) -> None:
"""从 Hybrid preproc_blocks 执行完整 finalize,供服务端完整路径和客户端复用。"""
build_para_blocks_from_preproc(pdf_info_list)
- merge_para_text_blocks(
- pdf_info_list,
- auto_merge_by_det=True,
- )
+ merge_para_text_blocks(pdf_info_list, auto_merge_by_det=True)
table_enable = get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
if table_enable:
@@ -186,12 +183,7 @@ def finalize_middle_json(
_vlm_ocr_enable: bool,
) -> None:
"""保持旧入口语义:服务端先做必要 post-OCR,再执行完整 finalize。"""
- apply_server_side_postprocess(
- pdf_info_list,
- hybrid_pipeline_model,
- _ocr_enable,
- _vlm_ocr_enable,
- )
+ apply_server_side_postprocess(pdf_info_list, hybrid_pipeline_model, _ocr_enable, _vlm_ocr_enable)
finalize_middle_json_from_preproc(pdf_info_list)
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 09de2a9f..cf8e6edd 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -351,7 +351,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
return spans
-def parse_list_block(list_block: dict[str, Any]) -> Block:
+def parse_list_block(list_block: dict[str, Any]) -> Block | None:
"""
递归解析嵌套列表结构,生成与VLM一致的blocks结构。
@@ -393,7 +393,7 @@ def parse_list_block(list_block: dict[str, Any]) -> Block:
return result
-def parse_index_block(index_block: dict[str, Any]) -> Block:
+def parse_index_block(index_block: dict[str, Any]) -> Block | None:
"""
递归解析嵌套索引结构(目录),生成与list一致的blocks结构。
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
index f74bee3c..c722bd52 100644
--- a/mineru/backend/pipeline/batch_analyze.py
+++ b/mineru/backend/pipeline/batch_analyze.py
@@ -82,7 +82,7 @@ class BatchAnalyze:
@staticmethod
def _apply_mask_boxes_to_image(
bgr_image: np.ndarray,
- mask_boxes: list[dict] | None,
+ mask_boxes: list[dict[str, Any]] | None,
) -> np.ndarray:
if not mask_boxes:
return bgr_image
@@ -106,14 +106,14 @@ class BatchAnalyze:
def _get_masked_det_image(
self,
bgr_image: np.ndarray,
- mask_boxes: list[dict] | None,
+ mask_boxes: list[dict[str, Any]] | None,
) -> np.ndarray:
if not self.mask_inline_formula_for_ocr_det:
return bgr_image
return self._apply_mask_boxes_to_image(bgr_image, mask_boxes)
@staticmethod
- def _prune_empty_ocr_text_blocks(layout_res: list[dict], ocr_enable: bool) -> None:
+ def _prune_empty_ocr_text_blocks(layout_res: list[dict[str, Any]], ocr_enable: bool) -> None:
if not ocr_enable or not layout_res:
return
@@ -265,10 +265,10 @@ class BatchAnalyze:
@classmethod
def _extract_table_inline_objects(
cls,
- layout_res: list[dict],
+ layout_res: list[dict[str, Any]],
np_img: np.ndarray,
formula_enable: bool,
- ) -> dict[int, list[dict]]:
+ ) -> dict[int, list[dict[str, Any]]]:
image_h, image_w = np_img.shape[:2]
image_size = (image_h, image_w)
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 90462f65..1cf504c6 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -126,10 +126,10 @@ class MagicModel:
score=block_score,
)
if self.__is_seal_layout_block(layout_det):
- block["sub_type"] = "seal"
+ block.sub_type = "seal"
self.page_blocks.append(block)
- self.page_blocks.sort(key=lambda x: x["index"])
+ self.page_blocks.sort(key=lambda x: x.index)
self.__build_page_blocks()
fallback_inline_caption_fragments(self.page_blocks, self.VISUAL_MAIN_TYPES)
fallback_leading_table_continuation_captions(self.page_blocks, self.VISUAL_MAIN_TYPES)
@@ -438,10 +438,10 @@ class MagicModel:
blocks=[body_block, *captions, *footnotes],
)
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"):
- two_layer_block["sub_type"] = block["sub_type"]
+ if block.score is not None:
+ two_layer_block.score = block.score
+ if original_block_type in [BlockType.IMAGE, BlockType.CHART] and block.sub_type:
+ two_layer_block.sub_type = block.sub_type
# 对blocks按index排序
two_layer_block["blocks"].sort(key=lambda x: x["index"])
rebuilt_page_blocks.append(two_layer_block)
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index 85158e3c..76a13e0b 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -346,7 +346,7 @@ def _normalize_text_content(content: str) -> str:
return full_to_half_exclude_marks(content or "")
-def _render_span(span: Span, escape_markdown: bool = True) -> str:
+def _render_span(span: Span, escape_markdown: bool = True) -> str | None:
# 将单个 span 渲染成 markdown 片段。
# 这里只负责“渲染成什么文本”,不决定后面是否补空格。
span_type = span.type
@@ -596,7 +596,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]]:
+) -> list[dict[str, Any]] | None:
para_type = para_block.type
para_content = None
if para_type in [
diff --git a/mineru/backend/utils/char_utils.py b/mineru/backend/utils/char_utils.py
index 66dacf94..c048dd8e 100644
--- a/mineru/backend/utils/char_utils.py
+++ b/mineru/backend/utils/char_utils.py
@@ -7,7 +7,7 @@ LINE_END_HYPHEN_CHARS = "-\u00ad\u2010\u2011\u2043"
LINE_END_HYPHEN_RE = re.compile(rf"[A-Za-z]+[{re.escape(LINE_END_HYPHEN_CHARS)}]\s*$")
-def _is_hyphen_at_line_end(line: str) -> bool:
+def is_hyphen_at_line_end(line: str) -> bool:
"""判断文本行是否以英文单词的跨行断词符结尾。
只识别字母后紧跟行末 hyphen 的断词场景,不处理词内连字符或普通破折号。
@@ -15,7 +15,7 @@ def _is_hyphen_at_line_end(line: str) -> bool:
return bool(LINE_END_HYPHEN_RE.search(line))
-def _full_to_half_exclude_marks(text: str) -> str:
+def full_to_half_exclude_marks(text: str) -> str:
"""Convert full-width characters to half-width characters using code point manipulation.
Args:
diff --git a/mineru/backend/utils/magic_model_utils.py b/mineru/backend/utils/magic_model_utils.py
index 1cd4728c..f9775780 100644
--- a/mineru/backend/utils/magic_model_utils.py
+++ b/mineru/backend/utils/magic_model_utils.py
@@ -3,12 +3,18 @@
包含两个MagicModel类中重复使用的方法和逻辑
"""
-from typing import Any, Callable, Dict, List
+from typing import Any, Callable, Dict, List, TypeVar
from loguru import logger
from .boxbase import bbox_center_distance, bbox_distance, is_in
+T = TypeVar("T")
+
+
+def _identical(x: T) -> T:
+ return x
+
def reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
@@ -60,9 +66,9 @@ def tie_up_category_by_index(
# 如果没有提供自定义提取函数,使用默认函数
if extract_subject_func is None:
- extract_subject_func = lambda x: x
+ extract_subject_func = _identical
if extract_object_func is None:
- extract_object_func = lambda x: x
+ extract_object_func = _identical
# 初始化结果字典,key为主体索引,value为关联信息
result_dict = {}
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 9fa01b27..0423494c 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, dict, Any, DataWriter | None, int], PageInfo],
+ page_cvt_fn: Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
finalize_fn: Callable[..., None],
**kwargs: Any,
) -> dict[str, Any]:
@@ -71,7 +71,7 @@ def append_pages(
pdf_doc: Any,
image_writer: DataWriter | None,
*,
- page_cvt_fn: Callable[[T, dict, Any, DataWriter | None, int], PageInfo],
+ page_cvt_fn: Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
page_start_index: int = 0,
progress_bar: Any = None,
**kwargs: Any,
diff --git a/mineru/backend/utils/ocr_det_utils.py b/mineru/backend/utils/ocr_det_utils.py
index 85e9327e..51066701 100644
--- a/mineru/backend/utils/ocr_det_utils.py
+++ b/mineru/backend/utils/ocr_det_utils.py
@@ -11,39 +11,49 @@ 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: tuple[float, float, float, 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/runtime_utils.py b/mineru/backend/utils/runtime_utils.py
index 748bae5e..8556a401 100644
--- a/mineru/backend/utils/runtime_utils.py
+++ b/mineru/backend/utils/runtime_utils.py
@@ -15,7 +15,7 @@ def cross_page_table_merge(pdf_info: list[PageInfo]) -> None:
"""Merge tables that span across multiple pages in a PDF document.
Args:
- pdf_info (list[dict]): A list of dictionaries containing information about each page in the PDF.
+ pdf_info (list[PageInfo]): A list of dictionaries containing information about each page in the PDF.
Returns:
None
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index 1b2b844c..b74489a1 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -12,6 +12,7 @@ import numpy as np
from loguru import logger
from ...utils.enum_class import BlockType, ContentType
+from ...types import Span
from ...utils.image_utils import calculate_contrast
from ...utils.pdf_image_tools import get_crop_img
from ...utils.pdf_text_tool import get_lines_from_chars, get_page_chars
@@ -39,12 +40,12 @@ def __replace_unicode(text: str) -> str:
def txt_spans_extract(
pdf_page: Any,
- spans: list[dict[str, Any]],
+ spans: list[Span],
pil_img: Any,
scale: int,
all_bboxes: list[tuple[Any, ...]],
all_discarded_blocks: list[tuple[Any, ...]],
-) -> list[dict[str, Any]]:
+) -> list[Span]:
page_char_count = None
textpage = None
try:
@@ -57,7 +58,7 @@ def txt_spans_extract(
if page_char_count is not None and page_char_count > MAX_NATIVE_TEXT_CHARS_PER_PAGE:
logger.info(f"Fallback to post-OCR in txt_spans_extract due to high char count: count_chars={page_char_count}")
- need_ocr_spans = [span for span in spans if span.get("type") == ContentType.TEXT]
+ need_ocr_spans = [span for span in spans if span.type == ContentType.TEXT]
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
page_chars = get_page_chars(
@@ -70,10 +71,10 @@ def txt_spans_extract(
# 计算所有sapn的高度的中位数
span_height_list = []
for span in spans:
- if span["type"] in [ContentType.TEXT]:
- span_height = span["bbox"][3] - span["bbox"][1]
- span["height"] = span_height
- span["width"] = span["bbox"][2] - span["bbox"][0]
+ if span.type in [ContentType.TEXT]:
+ span_height = span.bbox[3] - span.bbox[1]
+ span._extra["height"] = span_height
+ span._extra["width"] = span.bbox[2] - span.bbox[0]
span_height_list.append(span_height)
if len(span_height_list) == 0:
return spans
@@ -85,12 +86,12 @@ def txt_spans_extract(
# 纵向span的两个特征:1. 高度超过多个line 2. 高宽比超过某个值
vertical_spans = []
for span in spans:
- if span["type"] in [ContentType.TEXT]:
+ if span.type in [ContentType.TEXT]:
for block in all_bboxes + all_discarded_blocks:
if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:
continue
- if calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block[0:4]) > 0.5:
- if span["height"] > median_span_height * 2.3 and span["height"] > span["width"] * 2.3:
+ if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
+ if span._extra["height"] > median_span_height * 2.3 and span._extra["height"] > span._extra["width"] * 2.3:
vertical_spans.append(span)
elif block in all_bboxes:
useful_spans.append(span)
@@ -105,21 +106,21 @@ def txt_spans_extract(
]
for pdfium_line in page_all_lines:
for span in vertical_spans:
- if calculate_overlap_area_in_bbox1_area_ratio(pdfium_line["bbox"].bbox, span["bbox"]) > 0.5:
+ if calculate_overlap_area_in_bbox1_area_ratio(pdfium_line["bbox"].bbox, span.bbox) > 0.5:
for pdfium_span in pdfium_line["spans"]:
- span["content"] += pdfium_span["text"]
+ span.content += pdfium_span["text"]
break
for span in vertical_spans:
- if len(span["content"]) == 0:
+ if len(span.content) == 0:
spans.remove(span)
"""水平的span框先用char填充,再用ocr填充空的span框"""
new_spans = []
for span in useful_spans + unuseful_spans:
- if span["type"] in [ContentType.TEXT]:
- span["chars"] = []
+ if span.type in [ContentType.TEXT]:
+ span._extra["chars"] = []
new_spans.append(span)
need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)
@@ -136,17 +137,17 @@ def _is_supported_rotation(rotation: float) -> bool:
def _prepare_post_ocr_spans(
- need_ocr_spans: list[dict[str, Any]],
- spans: list[dict[str, Any]],
+ need_ocr_spans: list[Span],
+ spans: list[Span],
pil_img: Any,
scale: int,
-) -> list[dict[str, Any]]:
+) -> list[Span]:
if len(need_ocr_spans) == 0:
return spans
for span in need_ocr_spans:
# 对span的bbox截图再ocr
- span_pil_img = get_crop_img(span["bbox"], pil_img, scale)
+ span_pil_img = get_crop_img(span.bbox, pil_img, scale)
span_img = cv2.cvtColor(np.array(span_pil_img), cv2.COLOR_RGB2BGR)
# 计算span的对比度,低于0.17的span不进行ocr,等于0.17的临界框保留给后置OCR。
if calculate_contrast(span_img, img_mode="bgr") < 0.17:
@@ -154,9 +155,9 @@ def _prepare_post_ocr_spans(
spans.remove(span)
continue
- span["content"] = ""
- span["score"] = 1.0
- span["np_img"] = span_img
+ span.content = ""
+ span.score = 1.0
+ span._extra["np_img"] = span_img
return spans
@@ -164,27 +165,27 @@ def _prepare_post_ocr_spans(
class SpanBlockMatcher:
"""按 block 顺序消费 span,并用 y 方向索引减少无效重叠计算。"""
- def __init__(self, spans: list[dict[str, Any]]) -> None:
+ def __init__(self, spans: list[Span]) -> None:
self.spans = list(spans)
self.used_span_indices = set()
self.grid_size = self._get_grid_size(self.spans)
self.grid = self._build_grid(self.spans)
@staticmethod
- def _get_grid_size(spans: list[dict[str, Any]]) -> int:
+ def _get_grid_size(spans: list[Span]) -> int:
"""根据 span 高度估算索引网格大小,避免过细或过粗。"""
heights = [
- span["bbox"][3] - span["bbox"][1] for span in spans if span.get("bbox") and span["bbox"][3] > span["bbox"][1]
+ span.bbox[3] - span.bbox[1] for span in spans if span.bbox and span.bbox[3] > span.bbox[1]
]
if not heights:
return 1
return max(1, statistics.median(heights))
- def _build_grid(self, spans: list[dict[str, Any]]) -> dict[int, list[int]]:
+ def _build_grid(self, spans: list[Span]) -> dict[int, list[int]]:
"""将 span 按 y 方向网格登记,后续按 block bbox 快速取候选。"""
grid = collections.defaultdict(list)
for index, span in enumerate(spans):
- bbox = span.get("bbox")
+ bbox = span.bbox
if not bbox:
continue
start_cell, end_cell = self._cell_range(bbox)
@@ -192,7 +193,7 @@ class SpanBlockMatcher:
grid[cell_idx].append(index)
return grid
- def _cell_range(self, bbox: list[float]) -> tuple[int, int]:
+ def _cell_range(self, bbox: list[float] | tuple[float, ...]) -> tuple[int, int]:
"""计算 bbox 覆盖的 y 方向网格范围。"""
return (
int(bbox[1] / self.grid_size),
@@ -212,7 +213,7 @@ class SpanBlockMatcher:
block_bbox: list[float],
overlap_ratio_getter: Callable | None = None,
threshold: float = 0.5,
- ) -> list[dict[str, Any]]:
+ ) -> list[Span]:
"""返回当前 block 命中的 span,并标记为已消费以保持旧归属语义。"""
if overlap_ratio_getter is None:
overlap_ratio_getter = self._default_overlap_ratio
@@ -227,29 +228,29 @@ class SpanBlockMatcher:
self.used_span_indices.add(span_idx)
return block_spans
- def remaining_spans(self) -> list[dict[str, Any]]:
+ def remaining_spans(self) -> list[Span]:
"""返回尚未归属到任何 block 的 span,方便保持后续兼容。"""
return [span for index, span in enumerate(self.spans) if index not in self.used_span_indices]
@staticmethod
- def _default_overlap_ratio(span: dict[str, Any], block_bbox: list[float]) -> float:
+ def _default_overlap_ratio(span: Span, block_bbox: list[float]) -> float:
"""默认沿用旧逻辑:计算 span 面积中落入 block 的比例。"""
- return calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block_bbox)
+ return calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block_bbox)
def fill_char_in_spans(
- spans: list[dict[str, Any]],
+ spans: list[Span],
all_chars: list[dict[str, Any]],
median_span_height: float,
-) -> list[dict[str, Any]]:
+) -> list[Span]:
# 简单从上到下排一下序
- spans = sorted(spans, key=lambda x: x["bbox"][1])
+ spans = sorted(spans, key=lambda x: x.bbox[1])
grid_size = max(1, median_span_height)
grid = collections.defaultdict(list)
span_bboxes = []
for i, span in enumerate(spans):
- span_bbox = span["bbox"]
+ span_bbox = span.bbox
span_bboxes.append(span_bbox)
start_cell = int(span_bbox[1] / grid_size)
end_cell = int(span_bbox[3] / grid_size)
@@ -274,17 +275,17 @@ def fill_char_in_spans(
):
continue
if calculate_char_in_span(char_bbox, span_bbox, char["char"]):
- span["chars"].append(char)
+ span._extra["chars"].append(char)
break
need_ocr_spans = []
for span in spans:
chars_to_content(span)
# 有的span中虽然没有字但有一两个空的占位符,用宽高和content长度过滤
- if len(span["content"]) * span["height"] < span["width"] * 0.5:
+ if len(span.content) * span._extra["height"] < span._extra["width"] * 0.5:
# logger.info(f"maybe empty span: {len(span['content'])}, {span['height']}, {span['width']}")
need_ocr_spans.append(span)
- del span["height"], span["width"]
+ del span._extra["height"], span._extra["width"]
return need_ocr_spans
@@ -373,10 +374,10 @@ def calculate_char_in_span(
return False
-def chars_to_content(span: dict[str, Any]) -> None:
+def chars_to_content(span: Span) -> None:
# 检查span中的char是否为空
- if len(span["chars"]) != 0:
- chars = span["chars"]
+ if len(span._extra["chars"]) != 0:
+ chars = span._extra["chars"]
# 大多数情况下 char 已按 PDF 原始顺序进入,只有乱序时才排序。
if any(chars[idx]["char_idx"] > chars[idx + 1]["char_idx"] for idx in range(len(chars) - 1)):
chars = sorted(chars, key=lambda x: x["char_idx"])
@@ -405,6 +406,6 @@ def chars_to_content(span: dict[str, Any]) -> None:
content = "".join(parts)
content = __replace_unicode(content)
content = __replace_ligatures(content)
- span["content"] = content.strip()
+ span.content = content.strip()
- del span["chars"]
+ del span._extra["chars"]
diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.py
index 725ca7c2..701421ce 100644
--- a/mineru/backend/utils/table_merge.py
+++ b/mineru/backend/utils/table_merge.py
@@ -7,6 +7,7 @@ from typing import Any
from bs4 import BeautifulSoup, Tag
+from ...types import Block, PageInfo, Span
from ...utils.enum_class import BlockType, SplitFlag
from ..vlm.vlm_middle_json_mkcontent import merge_para_with_text
from .char_utils import full_to_half
@@ -54,8 +55,8 @@ class RowScanResult:
@dataclass
class TableMergeState:
- owner_block: dict[str, Any]
- body_span: dict[str, Any]
+ owner_block: Block
+ body_span: Span
soup: Any
tbody: Any
rows: list[Any]
@@ -171,40 +172,40 @@ def _build_front_cache(
return front_header_info, front_first_data_row_metrics
-def _find_table_body_block(table_block: dict[str, Any]) -> dict[str, Any] | None:
+def _find_table_body_block(table_block: Block) -> Block | None:
"""查找 table block 中的主体子块。"""
- for block in table_block["blocks"]:
- if block["type"] == BlockType.TABLE_BODY:
+ for block in table_block.blocks:
+ if block.type == BlockType.TABLE_BODY:
return block
return None
-def _build_post_body_child_index(table_block: dict[str, Any], offset: int) -> int | float | None:
+def _build_post_body_child_index(table_block: Block, offset: int) -> int | float | None:
"""为跨页搬运到上一页表格的子块生成表体后的安全 index。"""
body_block = _find_table_body_block(table_block)
if body_block is None:
return None
- body_index = body_block.get("index")
+ body_index = body_block.index
if not isinstance(body_index, (int, float)):
return None
return body_index + offset
-def _find_table_body_span(table_block: dict[str, Any]) -> dict[str, Any] | None:
+def _find_table_body_span(table_block: Block) -> Span | None:
body_block = _find_table_body_block(table_block)
- if body_block and body_block["lines"] and body_block["lines"][0]["spans"]:
- return body_block["lines"][0]["spans"][0]
+ if body_block and body_block.lines and body_block.lines[0].spans:
+ return body_block.lines[0].spans[0]
return None
-def _is_continuation_caption(caption_block: dict[str, Any]) -> bool:
+def _is_continuation_caption(caption_block: Block) -> bool:
"""判断 caption 文本是否带有续表标记。"""
return is_table_continuation_text(merge_para_with_text(caption_block))
-def _is_post_table_non_continuation_caption(table_block: dict[str, Any], caption_block: dict[str, Any]) -> bool:
+def _is_post_table_non_continuation_caption(table_block: Block, caption_block: Block) -> bool:
"""判断 caption 是否是误挂到表格下方的新段落标题。
这类 caption 位于 table body 下方,且不含续表标记;它不应作为
@@ -217,31 +218,29 @@ def _is_post_table_non_continuation_caption(table_block: dict[str, Any], caption
if body_block is None:
return False
- body_bbox = body_block.get("bbox")
- caption_bbox = caption_block.get("bbox")
+ body_bbox = body_block.bbox
+ caption_bbox = caption_block.bbox
if not body_bbox or not caption_bbox:
return False
return caption_bbox[1] >= body_bbox[3]
-def _get_post_table_caption_blocks(table_block: dict[str, Any]) -> list[dict[str, Any]]:
+def _get_post_table_caption_blocks(table_block: Block) -> list[Block]:
"""收集当前表格下方、需要恢复为普通文本的非续表 caption。"""
return [
block
- for block in table_block["blocks"]
- if block["type"] == BlockType.TABLE_CAPTION and _is_post_table_non_continuation_caption(table_block, block)
+ for block in table_block.blocks
+ if block.type == BlockType.TABLE_CAPTION and _is_post_table_non_continuation_caption(table_block, block)
]
-def _restore_post_table_captions_as_text(
- page_info: dict[str, Any], table_block: dict[str, Any], caption_blocks: list[dict[str, Any]]
-) -> None:
+def _restore_post_table_captions_as_text(page_info: PageInfo, table_block: Block, caption_blocks: list[Block]) -> None:
"""将误挂到表格下方的 caption 迁回当前页,作为独立 text block 输出。"""
if not caption_blocks:
return
- para_blocks = page_info.get("para_blocks", [])
+ para_blocks = page_info.para_blocks
try:
insert_idx = para_blocks.index(table_block) + 1
except ValueError:
@@ -250,12 +249,12 @@ def _restore_post_table_captions_as_text(
restored_blocks = []
for caption_block in caption_blocks:
text_block = deepcopy(caption_block)
- text_block["type"] = BlockType.TEXT
+ text_block.type = BlockType.TEXT
restored_blocks.append(text_block)
para_blocks[insert_idx:insert_idx] = restored_blocks
restored_caption_ids = {id(block) for block in caption_blocks}
- table_block["blocks"] = [block for block in table_block["blocks"] if id(block) not in restored_caption_ids]
+ table_block.blocks = [block for block in table_block.blocks if id(block) not in restored_caption_ids]
def _refresh_table_state_metrics(state: TableMergeState) -> None:
@@ -303,12 +302,12 @@ def build_table_state_from_html(
)
-def _build_table_state(table_block: dict[str, Any], max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:
+def _build_table_state(table_block: Block, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:
body_span = _find_table_body_span(table_block)
if body_span is None:
return None
- html = body_span.get("html", "")
+ html = body_span.html
if not html:
return None
@@ -334,7 +333,7 @@ def _build_table_state(table_block: dict[str, Any], max_header_rows: int = MAX_H
def _get_or_create_table_state(
- table_block: dict[str, Any],
+ table_block: Block,
state_cache: dict[int, TableMergeState],
max_header_rows: int = MAX_HEADER_ROWS,
) -> TableMergeState | None:
@@ -350,7 +349,7 @@ def _get_or_create_table_state(
def _serialize_table_state_html(state: TableMergeState) -> None:
- state.body_span["html"] = str(state.soup)
+ state.body_span._extra["html"] = str(state.soup)
state.dirty = False
@@ -687,8 +686,8 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeS
"For HTML-only states from build_table_state_from_html(), use can_merge_by_structure() instead."
)
- footnote_count = sum(1 for block in previous_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE)
- caption_blocks = [block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION]
+ footnote_count = sum(1 for block in previous_table_block.blocks if block.type == BlockType.TABLE_FOOTNOTE)
+ caption_blocks = [block for block in current_table_block.blocks if block.type == BlockType.TABLE_CAPTION]
merge_caption_blocks = [
block for block in caption_blocks if not _is_post_table_non_continuation_caption(current_table_block, block)
]
@@ -703,8 +702,8 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeS
elif footnote_count > 0:
return False
- x0_t1, _, x1_t1, _ = current_table_block["bbox"]
- x0_t2, _, x1_t2, _ = previous_table_block["bbox"]
+ x0_t1, _, x1_t1, _ = current_table_block.bbox
+ x0_t2, _, x1_t2, _ = previous_table_block.bbox
table1_width = x1_t1 - x0_t1
table2_width = x1_t2 - x0_t2
@@ -1000,8 +999,8 @@ def _apply_cell_merge(
def perform_table_merge(
previous_state: TableMergeState,
current_state: TableMergeState,
- previous_table_block: dict[str, Any],
- wait_merge_table_footnotes: list[dict[str, Any]],
+ previous_table_block: Block,
+ wait_merge_table_footnotes: list[Block],
) -> None:
"""执行表格合并操作."""
header_count, _, _ = detect_table_headers(previous_state, current_state)
@@ -1080,23 +1079,21 @@ def perform_table_merge(
previous_state.last_data_row_metrics = appended_scan.last_nonempty_row_metrics
previous_state.tail_occupied = appended_scan.tail_occupied
- previous_table_block["blocks"] = [
- block for block in previous_table_block["blocks"] if block["type"] != BlockType.TABLE_FOOTNOTE
- ]
+ previous_table_block.blocks = [block for block in previous_table_block.blocks if block.type != BlockType.TABLE_FOOTNOTE]
for footnote_offset, table_footnote in enumerate(wait_merge_table_footnotes, start=1):
temp_table_footnote = table_footnote.copy()
- temp_table_footnote[SplitFlag.CROSS_PAGE] = True
+ temp_table_footnote._extra[SplitFlag.CROSS_PAGE] = True
post_body_index = _build_post_body_child_index(previous_table_block, footnote_offset)
if post_body_index is None:
- temp_table_footnote.pop("index", None)
+ temp_table_footnote._extra.pop("index", None)
else:
- temp_table_footnote["index"] = post_body_index
- previous_table_block["blocks"].append(temp_table_footnote)
+ temp_table_footnote.index = post_body_index
+ previous_table_block.blocks.append(temp_table_footnote)
previous_state.dirty = True
-def merge_table(page_info_list: list[dict[str, Any]]) -> None:
+def merge_table(page_info_list: list[PageInfo]) -> None:
"""合并跨页表格."""
state_cache: dict[int, TableMergeState] = {}
merged_away_blocks: set[int] = set()
@@ -1108,14 +1105,14 @@ def merge_table(page_info_list: list[dict[str, Any]]) -> None:
page_info = page_info_list[page_idx]
previous_page_info = page_info_list[page_idx - 1]
- if not (page_info["para_blocks"] and page_info["para_blocks"][0]["type"] == BlockType.TABLE):
+ if not (page_info.para_blocks and page_info.para_blocks[0].type == BlockType.TABLE):
continue
- if not (previous_page_info["para_blocks"] and previous_page_info["para_blocks"][-1]["type"] == BlockType.TABLE):
+ if not (previous_page_info.para_blocks and previous_page_info.para_blocks[-1].type == BlockType.TABLE):
continue
- current_table_block = page_info["para_blocks"][0]
- previous_table_block = previous_page_info["para_blocks"][-1]
+ current_table_block = page_info.para_blocks[0]
+ previous_table_block = previous_page_info.para_blocks[-1]
current_state = _get_or_create_table_state(current_table_block, state_cache)
previous_state = _get_or_create_table_state(previous_table_block, state_cache)
@@ -1123,9 +1120,7 @@ def merge_table(page_info_list: list[dict[str, Any]]) -> None:
continue
post_table_caption_blocks = _get_post_table_caption_blocks(current_table_block)
- wait_merge_table_footnotes = [
- block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE
- ]
+ wait_merge_table_footnotes = [block for block in current_table_block.blocks if block.type == BlockType.TABLE_FOOTNOTE]
if not can_merge_tables(current_state, previous_state):
continue
@@ -1143,9 +1138,9 @@ def merge_table(page_info_list: list[dict[str, Any]]) -> None:
)
merged_away_blocks.add(id(current_table_block))
- for block in current_table_block["blocks"]:
- block["lines"] = []
- block[SplitFlag.LINES_DELETED] = True
+ for block in current_table_block.blocks:
+ block.lines = []
+ block._lines_deleted = True
for state in state_cache.values():
if state.dirty and id(state.owner_block) not in merged_away_blocks:
diff --git a/mineru/backend/vlm/utils.py b/mineru/backend/vlm/utils.py
index 371b03fa..6d1dd65e 100644
--- a/mineru/backend/vlm/utils.py
+++ b/mineru/backend/vlm/utils.py
@@ -126,7 +126,7 @@ def set_default_batch_size() -> int:
return batch_size
-def _get_device_config(device_type: str) -> dict | None:
+def _get_device_config(device_type: str) -> dict[str, Any] | None:
"""获取不同设备类型的配置参数"""
# 各设备类型的配置定义
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index 9f459809..c9680be4 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -2,14 +2,15 @@
import os
import re
from html import unescape
+from typing import Any
from loguru import logger
from ...types import Block, Line
-from ...utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
from ...utils.config_reader import get_formula_enable, get_latex_delimiter_config, get_table_enable
from ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode
from ...utils.language import detect_lang
+from ..utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
from ..utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
latex_delimiters_config = get_latex_delimiter_config()
@@ -88,8 +89,8 @@ def _build_media_path(img_buket_path: str, image_path: str) -> str:
return f"{img_buket_path}/{image_path}"
-def _apply_visual_sub_type(para_content: dict, para_block: Block) -> None:
- sub_type = para_block.get("sub_type")
+def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
+ sub_type = para_block.sub_type
if sub_type:
para_content["sub_type"] = sub_type
@@ -130,15 +131,15 @@ def _get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:
block
for _, block in sorted(
enumerate(blocks),
- key=lambda item: (item[1].get("index", float("inf")), item[0]),
+ key=lambda item: (item[1].index, item[0]),
)
]
def _render_code_block_markdown(block: Block, para_block: Block) -> str:
code_text = merge_para_with_text(block)
- if para_block.get("sub_type") == BlockType.CODE:
- guess_lang = para_block.get("guess_lang", "txt")
+ if para_block.sub_type == BlockType.CODE:
+ guess_lang = para_block.guess_lang or "txt"
return f"```{guess_lang}\n{code_text}\n```"
return code_text
@@ -171,11 +172,11 @@ def _render_visual_block_segments(
continue
rendered_segments.extend(
_build_visual_body_segments(
- span.get("image_path", ""),
- span.get("content", ""),
+ span.image_path,
+ span.content,
img_buket_path,
ContentType.IMAGE,
- summary_override=para_block.get("sub_type", ""),
+ summary_override=para_block.sub_type,
)
)
return rendered_segments
@@ -188,11 +189,11 @@ def _render_visual_block_segments(
continue
rendered_segments.extend(
_build_visual_body_segments(
- span.get("image_path", ""),
- span.get("content", ""),
+ span.image_path,
+ span.content,
img_buket_path,
ContentType.CHART,
- summary_override=para_block.get("sub_type", ""),
+ summary_override=para_block.sub_type,
)
)
return rendered_segments
@@ -203,17 +204,17 @@ def _render_visual_block_segments(
for span in line.spans:
if span.type != ContentType.TABLE:
continue
- if table_enable and span.get("html", ""):
+ if table_enable and span.html:
rendered_segments.append(
(
- _format_embedded_html(span["html"], img_buket_path),
+ _format_embedded_html(span.html, img_buket_path),
"html_block",
)
)
- elif span.get("image_path", ""):
+ elif span.image_path:
rendered_segments.append(
(
- f"![]({_build_media_path(img_buket_path, span['image_path'])})",
+ f"![]({_build_media_path(img_buket_path, span.image_path)})",
"markdown_line",
)
)
@@ -278,17 +279,17 @@ def merge_para_with_text(
span_type = span.type
content = ""
if span_type == ContentType.TEXT:
- content = span["content"]
+ content = span.content
if escape_markdown_text:
content = escape_conservative_markdown_text(content)
elif span_type == ContentType.INLINE_EQUATION:
- content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
+ content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"
elif span_type == ContentType.INTERLINE_EQUATION:
if formula_enable:
- content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
+ content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"
else:
- if span.get("image_path", ""):
- content = f"![]({img_buket_path}/{span['image_path']})"
+ if span.image_path:
+ content = f"![]({img_buket_path}/{span.image_path})"
content = content.strip()
if content:
@@ -317,10 +318,10 @@ def merge_para_with_text(
# 如果下一行的第一个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()
+ and para_block.lines[i + 1].spans
+ and para_block.lines[i + 1].spans[0].type == ContentType.TEXT
+ and para_block.lines[i + 1].spans[0].content
+ and para_block.lines[i + 1].spans[0].content[0].islower()
):
para_text += content[:-1]
else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
@@ -400,7 +401,7 @@ def mk_blocks_to_markdown(
return page_markdown
-def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]) -> dict:
+def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]) -> dict[str, Any]:
para_type = para_block.type
para_content = {}
if para_type in [
@@ -420,7 +421,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
elif para_type == BlockType.LIST:
para_content = {
"type": para_type,
- "sub_type": para_block.get("sub_type", ""),
+ "sub_type": para_block.sub_type,
"list_items": [],
}
for block in para_block.blocks:
@@ -459,14 +460,10 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
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"],
- img_buket_path,
- )
-
- if span.get("image_path", ""):
- para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ if span.html:
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_buket_path)
+ if span.image_path:
+ para_content["img_path"] = f"{img_buket_path}/{span.image_path}"
if block.type == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
@@ -488,19 +485,19 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
if block.type == BlockType.CHART_FOOTNOTE:
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: []}
+ 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:
code_text = merge_para_with_text(block)
- if para_block["sub_type"] == BlockType.CODE:
- guess_lang = para_block.get("guess_lang", "txt")
+ if para_block.sub_type == BlockType.CODE:
+ guess_lang = para_block.guess_lang or "txt"
code_text = f"```{guess_lang}\n{code_text}\n```"
para_content[BlockType.CODE_BODY] = code_text
if block.type == BlockType.CODE_CAPTION:
para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
page_width, page_height = page_size
- para_bbox = para_block.get("bbox")
+ para_bbox = para_block.bbox
if para_bbox:
x0, y0, x1, y1 = para_bbox
para_content["bbox"] = [
@@ -658,14 +655,14 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
code_caption.extend(merge_para_with_text_v2(block))
if block.type == BlockType.CODE_BODY:
code_content = merge_para_with_text_v2(block)
- sub_type = para_block["sub_type"]
+ sub_type = para_block.sub_type
if sub_type == BlockType.CODE:
para_content = {
"type": ContentTypeV2.CODE,
"content": {
"code_caption": code_caption,
"code_content": code_content,
- "code_language": para_block.get("guess_lang", "txt"),
+ "code_language": para_block.guess_lang or "txt",
},
}
elif sub_type == BlockType.ALGORITHM:
@@ -692,13 +689,13 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
},
}
elif para_type == BlockType.LIST:
- if "sub_type" in para_block:
- if para_block["sub_type"] == BlockType.REF_TEXT:
+ if para_block.sub_type:
+ if para_block.sub_type == BlockType.REF_TEXT:
list_type = ContentTypeV2.LIST_REF
- elif para_block["sub_type"] == BlockType.TEXT:
+ elif para_block.sub_type == BlockType.TEXT:
list_type = ContentTypeV2.LIST_TEXT
else:
- raise ValueError(f"Unknown list sub_type: {para_block['sub_type']}")
+ raise ValueError(f"Unknown list sub_type: {para_block.sub_type}")
else:
list_type = ContentTypeV2.LIST_TEXT
list_items = []
@@ -720,7 +717,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
}
page_width, page_height = page_size
- para_bbox = para_block.get("bbox")
+ para_bbox = para_block.bbox
if para_bbox:
x0, y0, x1, y1 = para_bbox
para_content["bbox"] = [
@@ -749,15 +746,15 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
for span in line.spans:
span_type = span.type
if span_type == ContentType.TABLE:
- return span.get("image_path", ""), span.get("html", "")
+ return span.image_path, span.html
elif span_type == ContentType.CHART:
- return span.get("image_path", ""), span.get("content", "")
+ return span.image_path, span.content
elif span_type == ContentType.IMAGE:
- return span.get("image_path", ""), span.get("content", "")
+ return span.image_path, span.content
elif span_type == ContentType.INTERLINE_EQUATION:
- return span.get("image_path", ""), span.get("content", "")
+ return span.image_path, span.content
elif span_type == ContentType.TEXT:
- return "", span.get("content", "")
+ return "", span.content
return "", ""
# 处理嵌套的 blocks 结构
@@ -779,8 +776,8 @@ def merge_para_with_text_v2(para_block: Block) -> str:
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"]
+ span.content = _normalize_text_content(span.content)
+ block_text += span.content
block_lang = detect_lang(block_text)
para_content = []
@@ -788,7 +785,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
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.content.strip():
if span_type == ContentType.TEXT:
if para_type == BlockType.PHONETIC:
span_type = ContentTypeV2.SPAN_PHONETIC
@@ -809,29 +806,29 @@ def merge_para_with_text_v2(para_block: Block) -> str:
if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
if has_following_joinable_span and not is_last_span:
- span_content = f"{span['content']} "
+ span_content = f"{span.content} "
else:
- span_content = span["content"]
+ span_content = span.content
else:
# 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
- if is_last_span and is_hyphen_at_line_end(span["content"]):
+ 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()
+ and para_block.lines[i + 1].spans
+ and para_block.lines[i + 1].spans[0].type == ContentType.TEXT
+ and para_block.lines[i + 1].spans[0].content
+ and para_block.lines[i + 1].spans[0].content[0].islower()
):
- span_content = span["content"][:-1]
+ span_content = span.content[:-1]
else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
- span_content = span["content"]
+ span_content = span.content
else:
# 西方文本语境下content间需要空格分隔
if has_following_joinable_span:
- span_content = f"{span['content']} "
+ span_content = f"{span.content} "
else:
- span_content = span["content"]
+ span_content = span.content
if para_content and para_content[-1]["type"] == span_type:
# 合并相同类型的span
@@ -847,10 +844,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
ContentTypeV2.SPAN_PHONETIC,
ContentTypeV2.SPAN_EQUATION_INLINE,
]:
- span_content = {
- "type": span_type,
- "content": span["content"],
- }
+ span_content = {"type": span_type, "content": span.content}
para_content.append(span_content)
else:
logger.warning(f"Unknown span type in merge_para_with_text_v2: {span_type}")
@@ -901,7 +895,9 @@ def union_make(
def get_title_level(block: Block) -> int:
- title_level = block.get("level", 1)
+ title_level = block.level
+ if title_level is None:
+ title_level = 1
if title_level > 4:
title_level = 4
elif title_level < 1:
diff --git a/mineru/parser/parse_result.py b/mineru/parser/parse_result.py
index d491e94e..851c1d9c 100644
--- a/mineru/parser/parse_result.py
+++ b/mineru/parser/parse_result.py
@@ -8,9 +8,10 @@ import re
from dataclasses import dataclass
from typing import Any
+from mineru.types import PageInfo
+
from ..utils.enum_class import MakeMode
from ..utils.pdf_document import PDFDocument
-from mineru.types import PageInfo
_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)
@@ -63,11 +64,21 @@ class ParseResult:
_model_output: Any = None
_images_cache: dict[str, bytes] | None = None
- def as_dict(self) -> dict:
+ @staticmethod
+ def from_dict(d: dict[str, Any]) -> "ParseResult":
+ # TODO
+ ...
+
+ def to_dict(self) -> dict[str, Any]:
return {"pdf_info": [dataclasses.asdict(p) for p in self.pages]}
- def json(self) -> str:
- return json.dumps(self.as_dict(), ensure_ascii=False, indent=2)
+ @staticmethod
+ def from_json(s: str) -> "ParseResult":
+ # TODO
+ ...
+
+ def to_json(self) -> str:
+ return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
def markdown(self) -> str:
union_make = _load_union_make(self._backend)
diff --git a/mineru/server/services/parse_svc.py b/mineru/server/services/parse_svc.py
index 410b27f9..51f517d7 100644
--- a/mineru/server/services/parse_svc.py
+++ b/mineru/server/services/parse_svc.py
@@ -7,7 +7,8 @@ import os
import time
from pathlib import Path
-from mineru.constants import ParseStatus, TIER_ORDER, Tier
+from mineru.constants import TIER_ORDER, ParseStatus, Tier
+
from ..core.file_io import compute_sha256, extract_metadata, get_file_stat
@@ -148,9 +149,16 @@ class ParseService:
"birthtime_ms, sha256, watch_id, first_seen_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
- path, Path(path).name, Path(path).suffix.lstrip(".").lower(),
- stat["size_bytes"], stat["mtime_ms"], stat["birthtime_ms"],
- sha256, watch_id, now, now,
+ path,
+ Path(path).name,
+ Path(path).suffix.lstrip(".").lower(),
+ stat["size_bytes"],
+ stat["mtime_ms"],
+ stat["birthtime_ms"],
+ sha256,
+ watch_id,
+ now,
+ now,
),
)
return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))
@@ -234,8 +242,7 @@ class ParseService:
# insert parse batch
pages_str = expand_pages(initial_pages, page_count or 1)
await self.db.execute(
- "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) "
- "VALUES (?, ?, ?, ?, 0, ?, ?)",
+ "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)",
(sha256, tier, pages_str, ParseStatus.PENDING, now, now),
)
@@ -248,18 +255,14 @@ class ParseService:
# ── parse request ───────────────────────────────────────────
- async def request_parse(self, path: str, *, tier: str | None = None,
- pages: str | None = None, force: bool = False) -> dict:
+ async def request_parse(self, path: str, *, tier: str | None = None, pages: str | None = None, force: bool = False) -> dict:
"""Handle a parse request from CLI. Returns info for status polling."""
# ensure file is registered
- file_row = await self.db.fetchone(
- "SELECT * FROM files WHERE path=? AND scan_status='active'", (path,)
- )
+ file_row = await self.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status='active'", (path,))
if file_row is None or file_row["sha256"] is None:
file_row = await self.register_file(path)
if file_row is None:
- return {"sha256": "", "tier": tier or "", "status": "error",
- "tip": "File could not be registered."}
+ return {"sha256": "", "tier": tier or "", "status": "error", "tip": "File could not be registered."}
sha256 = file_row["sha256"]
doc = await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,))
@@ -322,8 +325,7 @@ class ParseService:
# insert new batch
now = _now_ms()
await self.db.execute(
- "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) "
- "VALUES (?, ?, ?, ?, 1, ?, ?)",
+ "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?)",
(sha256, requested_tier, pages_str, ParseStatus.PENDING, now, now),
)
@@ -339,8 +341,7 @@ class ParseService:
async def get_queue_length(self) -> int:
timeout_ms = _now_ms() - 30 * 60 * 1000 # 30min lock timeout
row = await self.db.fetchone(
- "SELECT COUNT(*) as cnt FROM parses WHERE status=? "
- "AND (locked_at IS NULL OR locked_at < ?)",
+ "SELECT COUNT(*) as cnt FROM parses WHERE status=? AND (locked_at IS NULL OR locked_at < ?)",
(ParseStatus.PENDING, timeout_ms),
)
return row["cnt"] if row else 0
@@ -365,9 +366,7 @@ class ParseService:
pages = task["pages"]
# guard
- current = await self.db.fetchone(
- "SELECT status FROM parses WHERE id=?", (task["id"],)
- )
+ current = await self.db.fetchone("SELECT status FROM parses WHERE id=?", (task["id"],))
if current is None or current["status"] != ParseStatus.PARSING:
return False
@@ -430,8 +429,8 @@ class ParseService:
json_path = os.path.join(output_dir, f"{pages_key}.json")
new_pages: list[dict] = []
for r in results:
- if hasattr(r, "as_dict"):
- new_pages.extend(r.as_dict().get("pdf_info", []))
+ if hasattr(r, "to_dict"):
+ new_pages.extend(r.to_dict().get("pdf_info", []))
os.makedirs(output_dir, exist_ok=True)
try:
@@ -457,8 +456,7 @@ class ParseService:
async def get_parse_status(self, sha256: str, tier: str) -> dict | None:
"""Get aggregate status for a doc+tier. Returns latest batch info."""
done = await self.db.fetchone(
- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' "
- "ORDER BY done_at DESC LIMIT 1",
+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' ORDER BY done_at DESC LIMIT 1",
(sha256, tier),
)
if done:
@@ -473,8 +471,7 @@ class ParseService:
return {"sha256": sha256, "tier": tier, "status": active["status"], "pages": active["pages"]}
failed = await self.db.fetchone(
- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='failed' "
- "ORDER BY created_at DESC LIMIT 1",
+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='failed' ORDER BY created_at DESC LIMIT 1",
(sha256, tier),
)
if failed:
diff --git a/mineru/utils/cli_parser.py b/mineru/utils/cli_parser.py
index 2278a001..0a6786a3 100644
--- a/mineru/utils/cli_parser.py
+++ b/mineru/utils/cli_parser.py
@@ -1,5 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
from collections.abc import Sequence
+from typing import Any
import click
@@ -22,7 +23,7 @@ def _coerce_cli_value(raw_value: str) -> bool | float | int | str:
return raw_value
-def parse_unknown_args(args: Sequence[str]) -> dict:
+def parse_unknown_args(args: Sequence[str]) -> dict[str, Any]:
"""Parse unknown click args into keyword arguments."""
extra_kwargs = {}
i = 0
@@ -52,5 +53,5 @@ def parse_unknown_args(args: Sequence[str]) -> dict:
return extra_kwargs
-def arg_parse(ctx: "click.Context") -> dict:
+def arg_parse(ctx: "click.Context") -> dict[str, Any]:
return parse_unknown_args(ctx.args)
diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py
index a25401f3..0fb82ec8 100644
--- a/mineru/utils/config_reader.py
+++ b/mineru/utils/config_reader.py
@@ -79,37 +79,37 @@ def get_device() -> str:
if device_mode is not None:
return device_mode
try:
- if torch.cuda.is_available():
+ if torch.cuda.is_available(): # type: ignore
return "cuda"
except Exception:
pass
try:
- if torch.backends.mps.is_available():
+ if torch.backends.mps.is_available(): # type: ignore
return "mps"
except Exception:
pass
try:
- if torch_npu.npu.is_available():
+ if torch_npu.npu.is_available(): # type: ignore
return "npu"
except Exception:
pass
try:
- if torch.gcu.is_available():
+ if torch.gcu.is_available(): # type: ignore
return "gcu"
except Exception:
pass
try:
- if torch.musa.is_available():
+ if torch.musa.is_available(): # type: ignore
return "musa"
except Exception:
pass
try:
- if torch.mlu.is_available():
+ if torch.mlu.is_available(): # type: ignore
return "mlu"
except Exception:
pass
try:
- if torch.sdaa.is_available():
+ if torch.sdaa.is_available(): # type: ignore
return "sdaa"
except Exception:
pass
diff --git a/mineru/utils/cut_image.py b/mineru/utils/cut_image.py
index 4f705c2c..dc04cd61 100644
--- a/mineru/utils/cut_image.py
+++ b/mineru/utils/cut_image.py
@@ -1,36 +1,44 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
from typing import Any
from loguru import logger
+from ..types import Span
from .pdf_image_tools import cut_image
def cut_image_and_table(
- span: dict[str, Any],
+ span: Span,
page_pil_img: Any,
page_img_md5: str,
page_id: int,
image_writer: Any,
scale: int = 2,
-) -> dict[str, Any]:
+) -> Span:
- def return_path(path_type: str) -> str: # noqa: ANN202
+ def return_path(path_type: str) -> str:
return f"{path_type}/{page_img_md5}"
- span_type = span["type"]
+ span_type = span.type
- if not check_img_bbox(span["bbox"]) or not image_writer:
- span["image_path"] = ""
+ if not check_img_bbox(span.bbox) or not image_writer:
+ span._extra["image_path"] = ""
else:
- span["image_path"] = cut_image(
- span["bbox"], page_id, page_pil_img, return_path=return_path(span_type), image_writer=image_writer, scale=scale
+ span._extra["image_path"] = cut_image(
+ span.bbox,
+ page_id,
+ page_pil_img,
+ return_path=return_path(span_type),
+ image_writer=image_writer,
+ scale=scale,
)
return span
-def check_img_bbox(bbox: list[float]) -> bool:
+def check_img_bbox(bbox: tuple[float, float, float, float]) -> bool:
if any([bbox[0] >= bbox[2], bbox[1] >= bbox[3]]):
logger.warning(f"image_bboxes: 错误的box, {bbox}")
return False
diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.py
index fd7aacba..dac45ce8 100644
--- a/mineru/utils/draw_bbox.py
+++ b/mineru/utils/draw_bbox.py
@@ -9,6 +9,7 @@ from loguru import logger
from pypdf import PageObject, PdfReader, PdfWriter
from reportlab.pdfgen import canvas
+from ..types import Block, PageInfo, Span
from .enum_class import BlockType, ContentType, SplitFlag
# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。
@@ -31,9 +32,9 @@ DIRECT_LAYOUT_BBOX_BLOCK_TYPES = TEXT_LIKE_BLOCK_TYPES_FOR_BBOX | {
SPAN_SOURCE_BLOCK_TYPES = DIRECT_LAYOUT_BBOX_BLOCK_TYPES
-def _get_layout_source_blocks(page: dict[str, Any]) -> list[dict[str, Any]]:
+def _get_layout_source_blocks(page: PageInfo) -> list[Block]:
"""获取 layout.pdf 的页内原始布局块,避免段落合并后跨页子项串页绘制。"""
- return page.get("preproc_blocks", [])
+ return page.preproc_blocks
def cal_canvas_rect(page: Any, bbox: list[float]) -> list[float]:
@@ -120,7 +121,7 @@ def draw_bbox_with_number(
new_rgb = [float(color) / 255 for color in rgb_config]
page_data = bbox_list[i]
# 强制转换为 float
- page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
+ # page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
for j, bbox in enumerate(page_data):
# 确保bbox的每个元素都是float
@@ -161,7 +162,7 @@ def draw_bbox_with_number(
def draw_layout_bbox(
- pdf_info: list[dict[str, Any]],
+ pdf_info: list[PageInfo],
pdf_bytes: bytes,
out_path: str,
filename: str,
@@ -189,65 +190,65 @@ def draw_layout_bbox(
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"]
- if block["type"] == BlockType.TABLE:
- for nested_block in block["blocks"]:
- bbox = nested_block["bbox"]
- if nested_block["type"] == BlockType.TABLE_BODY:
+ bbox = block.bbox
+ if block.type == BlockType.TABLE:
+ for nested_block in block.blocks:
+ bbox = nested_block.bbox
+ if nested_block.type == BlockType.TABLE_BODY:
tables_body.append(bbox)
- elif nested_block["type"] == BlockType.TABLE_CAPTION:
+ elif nested_block.type == BlockType.TABLE_CAPTION:
tables_caption.append(bbox)
- elif nested_block["type"] == BlockType.TABLE_FOOTNOTE:
- if nested_block.get(SplitFlag.CROSS_PAGE, False):
+ elif nested_block.type == BlockType.TABLE_FOOTNOTE:
+ if nested_block._extra.get(SplitFlag.CROSS_PAGE, False):
continue
tables_footnote.append(bbox)
- elif block["type"] == BlockType.IMAGE:
- for nested_block in block["blocks"]:
- bbox = nested_block["bbox"]
- if nested_block["type"] == BlockType.IMAGE_BODY:
+ elif block.type == BlockType.IMAGE:
+ for nested_block in block.blocks:
+ bbox = nested_block.bbox
+ if nested_block.type == BlockType.IMAGE_BODY:
imgs_body.append(bbox)
- elif nested_block["type"] == BlockType.IMAGE_CAPTION:
+ elif nested_block.type == BlockType.IMAGE_CAPTION:
imgs_caption.append(bbox)
- elif nested_block["type"] == BlockType.IMAGE_FOOTNOTE:
+ elif nested_block.type == BlockType.IMAGE_FOOTNOTE:
imgs_footnote.append(bbox)
- elif block["type"] == BlockType.CODE:
- for nested_block in block["blocks"]:
- if nested_block["type"] == BlockType.CODE_BODY:
- bbox = nested_block["bbox"]
+ elif block.type == BlockType.CODE:
+ for nested_block in block.blocks:
+ if nested_block.type == BlockType.CODE_BODY:
+ bbox = nested_block.bbox
codes_body.append(bbox)
- elif nested_block["type"] == BlockType.CODE_CAPTION:
- bbox = nested_block["bbox"]
+ elif nested_block.type == BlockType.CODE_CAPTION:
+ bbox = nested_block.bbox
codes_caption.append(bbox)
- elif nested_block["type"] == BlockType.CODE_FOOTNOTE:
- bbox = nested_block["bbox"]
+ elif nested_block.type == BlockType.CODE_FOOTNOTE:
+ bbox = nested_block.bbox
codes_footnote.append(bbox)
- elif block["type"] == BlockType.CHART:
- for nested_block in block["blocks"]:
- if nested_block["type"] == BlockType.CHART_BODY:
- bbox = nested_block["bbox"]
+ elif block.type == BlockType.CHART:
+ for nested_block in block.blocks:
+ if nested_block.type == BlockType.CHART_BODY:
+ bbox = nested_block.bbox
imgs_body.append(bbox)
- elif nested_block["type"] == BlockType.CHART_CAPTION:
- bbox = nested_block["bbox"]
+ elif nested_block.type == BlockType.CHART_CAPTION:
+ bbox = nested_block.bbox
imgs_caption.append(bbox)
- elif nested_block["type"] == BlockType.CHART_FOOTNOTE:
- bbox = nested_block["bbox"]
+ elif nested_block.type == BlockType.CHART_FOOTNOTE:
+ bbox = nested_block.bbox
imgs_footnote.append(bbox)
- elif block["type"] == BlockType.TITLE:
+ elif block.type == BlockType.TITLE:
titles.append(bbox)
- elif block["type"] in TEXT_LIKE_BLOCK_TYPES_FOR_BBOX:
+ elif block.type in TEXT_LIKE_BLOCK_TYPES_FOR_BBOX:
texts.append(bbox)
- elif block["type"] == BlockType.INTERLINE_EQUATION:
+ elif block.type == BlockType.INTERLINE_EQUATION:
interline_equations.append(bbox)
- elif block["type"] == BlockType.LIST:
+ elif block.type == BlockType.LIST:
lists.append(bbox)
- if "blocks" in block:
- for sub_block in block["blocks"]:
- list_items.append(sub_block["bbox"])
- elif block["type"] == BlockType.INDEX:
+ if block.blocks:
+ for sub_block in block.blocks:
+ list_items.append(sub_block.bbox)
+ elif block.type == BlockType.INDEX:
indices.append(bbox)
tables_body_list.append(tables_body)
@@ -271,14 +272,14 @@ def draw_layout_bbox(
for page in pdf_info:
page_block_list = []
for block in _get_layout_source_blocks(page):
- if block["type"] in DIRECT_LAYOUT_BBOX_BLOCK_TYPES:
- bbox = block["bbox"]
+ if block.type in DIRECT_LAYOUT_BBOX_BLOCK_TYPES:
+ bbox = block.bbox
page_block_list.append(bbox)
- elif block["type"] in [BlockType.IMAGE, BlockType.CHART, BlockType.CODE, BlockType.TABLE]:
- for sub_block in block["blocks"]:
- if sub_block.get(SplitFlag.CROSS_PAGE, False):
+ elif block.type in [BlockType.IMAGE, BlockType.CHART, BlockType.CODE, BlockType.TABLE]:
+ for sub_block in block.blocks:
+ if sub_block._extra.get(SplitFlag.CROSS_PAGE, False):
continue
- bbox = sub_block["bbox"]
+ bbox = sub_block.bbox
page_block_list.append(bbox)
layout_bbox_list.append(page_block_list)
@@ -337,7 +338,7 @@ def draw_layout_bbox(
def draw_span_bbox(
- pdf_info: list[dict[str, Any]],
+ pdf_info: list[PageInfo],
pdf_bytes: bytes,
out_path: str,
filename: str,
@@ -349,17 +350,17 @@ def draw_span_bbox(
table_list = []
dropped_list = []
- def get_span_info(span: dict[str, Any]) -> None: # noqa: ANN202
- 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"])
+ def get_span_info(span: Span) -> None: # noqa: ANN202
+ 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 = []
@@ -370,22 +371,22 @@ def draw_span_bbox(
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.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:
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)
diff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.py
index 93c6af9d..404ab913 100644
--- a/mineru/utils/llm_aided.py
+++ b/mineru/utils/llm_aided.py
@@ -1,14 +1,16 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
+from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
-from typing import Any, Callable
+from typing import Any
import json_repair
from loguru import logger
from openai import OpenAI
from ..backend.pipeline.pipeline_middle_json_mkcontent import merge_para_with_text
+from ..types import Block, PageInfo
from .enum_class import BlockType
TITLE_BLOCK_TYPES = {
@@ -20,15 +22,14 @@ TITLE_BLOCK_TYPES = {
MAX_TITLE_GROUP_WORKERS = 4
-def _get_title_line_avg_height(block: dict[str, Any]) -> float:
- line_avg_height = block.get("line_avg_height")
- if isinstance(line_avg_height, (int, float)) and line_avg_height > 0:
- return line_avg_height
+def _get_title_line_avg_height(block: Block) -> float:
+ if block._line_avg_height > 0:
+ return block._line_avg_height
title_block_line_height_list = []
- for line in block.get("lines", []):
+ for line in block.lines:
# 标题行高是 LLM prompt 的几何提示,这里只消费有效 bbox,不回写 middle json。
- bbox = line.get("bbox")
+ bbox = line.bbox
if not bbox or len(bbox) < 4:
continue
line_height = bbox[3] - bbox[1]
@@ -38,21 +39,21 @@ def _get_title_line_avg_height(block: dict[str, Any]) -> float:
if len(title_block_line_height_list) > 0:
return sum(title_block_line_height_list) / len(title_block_line_height_list)
- bbox = block.get("bbox")
+ bbox = block.bbox
if bbox and len(bbox) >= 4:
return max(0, int(bbox[3] - bbox[1]))
return 0
def _collect_title_block_refs(
- page_info_list: list[dict[str, Any]],
-) -> tuple[list[tuple[dict[str, Any], dict[str, Any]]], set[Any]]:
+ page_info_list: list[PageInfo],
+) -> tuple[list[tuple[PageInfo, Block]], set[Any]]:
title_block_refs = []
title_types = set()
for page_info in page_info_list:
- for block in page_info.get("para_blocks", []):
- block_type = block.get("type")
+ for block in page_info.para_blocks:
+ block_type = block.type
if block_type in TITLE_BLOCK_TYPES:
title_block_refs.append((page_info, block))
title_types.add(block_type)
@@ -60,14 +61,14 @@ def _collect_title_block_refs(
return title_block_refs, title_types
-def _build_title_dict(title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]]) -> dict[str, list[Any]]:
+def _build_title_dict(title_block_refs: list[tuple[PageInfo, Block]]) -> dict[str, list[Any]]:
title_dict = {}
for i, (page_info, block) in enumerate(title_block_refs):
title_dict[str(i)] = [
merge_para_with_text(block),
_get_title_line_avg_height(block),
- int(page_info["page_idx"]) + 1,
+ page_info.page_idx + 1,
]
return title_dict
@@ -221,78 +222,74 @@ def _request_title_levels(
return None
-def _apply_levels_to_blocks(
- title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], levels_by_index: dict[int, int] | None
-) -> None:
+def _apply_levels_to_blocks(title_block_refs: list[tuple[PageInfo, Block]], levels_by_index: dict[int, int] | None) -> None:
if levels_by_index is None:
return
for i, (_, block) in enumerate(title_block_refs):
- block["level"] = int(levels_by_index[i])
+ block.level = int(levels_by_index[i])
-def _normalize_title_types(title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]]) -> None:
+def _normalize_title_types(title_block_refs: list[tuple[PageInfo, Block]]) -> None:
for _, block in title_block_refs:
- if block.get("type") in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE]:
- block["type"] = BlockType.TITLE
+ if block.type in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE]:
+ block.type = BlockType.TITLE
-def _get_title_block_identity(block: dict[str, Any]) -> tuple[str, int] | tuple[str, tuple[Any, ...], str]:
- block_index = block.get("index")
+def _get_title_block_identity(block: Block) -> tuple[str, int] | tuple[str, tuple[float, float, float, float], str]:
+ block_index = block.index
if block_index is not None:
return ("index", block_index)
return (
"bbox_text",
- tuple(block.get("bbox", [])),
+ block.bbox,
merge_para_with_text(block),
)
-def _sync_para_titles_to_preproc(page_info_list: list[dict[str, Any]]) -> None:
+def _sync_para_titles_to_preproc(page_info_list: list[PageInfo]) -> None:
for page_info in page_info_list:
para_title_map = {}
- for block in page_info.get("para_blocks", []):
- if block.get("type") in TITLE_BLOCK_TYPES:
+ for block in page_info.para_blocks:
+ if block.type in TITLE_BLOCK_TYPES:
para_title_map[_get_title_block_identity(block)] = block
if len(para_title_map) == 0:
continue
- for block in page_info.get("preproc_blocks", []):
- if block.get("type") not in TITLE_BLOCK_TYPES:
+ for block in page_info.preproc_blocks:
+ if block.type not in TITLE_BLOCK_TYPES:
continue
para_block = para_title_map.get(_get_title_block_identity(block))
if para_block is None:
continue
- block["type"] = para_block.get("type", block.get("type"))
- if "level" in para_block:
- block["level"] = para_block["level"]
+ block.type = para_block.type
+ if para_block.level is not None:
+ block.level = para_block.level
-def _run_single_pass_title_leveling(
- title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]
-) -> None:
+def _run_single_pass_title_leveling(title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]) -> None:
title_dict = _build_title_dict(title_block_refs)
levels_by_index = _request_title_levels(title_aided_config, title_dict)
_apply_levels_to_blocks(title_block_refs, levels_by_index)
def _split_paragraph_title_groups(
- title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]],
-) -> list[list[tuple[dict[str, Any], dict[str, Any]]]]:
+ title_block_refs: list[tuple[PageInfo, Block]],
+) -> list[list[tuple[PageInfo, Block]]]:
groups = []
current_group = []
for title_ref in title_block_refs:
_, block = title_ref
- if block.get("type") == BlockType.DOC_TITLE:
+ if block.type == BlockType.DOC_TITLE:
if current_group:
groups.append(current_group)
current_group = []
- elif block.get("type") == BlockType.PARAGRAPH_TITLE:
+ elif block.type == BlockType.PARAGRAPH_TITLE:
current_group.append(title_ref)
if current_group:
@@ -309,7 +306,7 @@ def _offset_paragraph_title_levels(levels_by_index: dict[int, int] | None) -> di
def _request_paragraph_group_levels(
- title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]
+ title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]
) -> dict[int, int] | None:
title_dict = _build_title_dict(title_block_refs)
levels_by_index = _request_title_levels(
@@ -320,14 +317,12 @@ def _request_paragraph_group_levels(
return _offset_paragraph_title_levels(levels_by_index)
-def _run_grouped_title_leveling(
- title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]
-) -> None:
+def _run_grouped_title_leveling(title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]) -> None:
doc_title_refs = []
for title_ref in title_block_refs:
_, block = title_ref
- if block.get("type") == BlockType.DOC_TITLE:
- block["level"] = 1
+ if block.type == BlockType.DOC_TITLE:
+ block.level = 1
doc_title_refs.append(title_ref)
paragraph_title_groups = _split_paragraph_title_groups(title_block_refs)
@@ -358,7 +353,7 @@ def _run_grouped_title_leveling(
_normalize_title_types(title_group)
-def llm_aided_title(page_info_list: list[dict[str, Any]], title_aided_config: dict[str, Any]) -> None:
+def llm_aided_title(page_info_list: list[PageInfo], title_aided_config: dict[str, Any]) -> None:
title_block_refs, title_types = _collect_title_block_refs(page_info_list)
if len(title_block_refs) == 0:
logger.info("No titles detected, skipping LLM-aided title optimization.")
@@ -377,8 +372,8 @@ def llm_aided_title(page_info_list: list[dict[str, Any]], title_aided_config: di
title_refs_for_llm = []
for title_ref in title_block_refs:
_, block = title_ref
- if block.get("type") == BlockType.DOC_TITLE:
- block["level"] = 1
+ if block.type == BlockType.DOC_TITLE:
+ block.level = 1
doc_title_refs.append(title_ref)
else:
title_refs_for_llm.append(title_ref)
diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.py
index 2f70d93d..9df9d08c 100644
--- a/mineru/utils/model_utils.py
+++ b/mineru/utils/model_utils.py
@@ -190,26 +190,26 @@ def get_res_list_from_layout_res(
def clean_memory(device: str = "cuda") -> None:
if str(device).startswith("cuda"):
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
+ if torch.cuda.is_available(): # type: ignore
+ torch.cuda.empty_cache() # type: ignore
# torch.cuda.ipc_collect()
elif str(device).startswith("npu"):
- if torch_npu.npu.is_available():
- torch_npu.npu.empty_cache()
+ if torch_npu.npu.is_available(): # type: ignore
+ torch_npu.npu.empty_cache() # type: ignore
elif str(device).startswith("mps"):
- torch.mps.empty_cache()
+ torch.mps.empty_cache() # type: ignore
elif str(device).startswith("gcu"):
- if torch.gcu.is_available():
- torch.gcu.empty_cache()
+ if torch.gcu.is_available(): # type: ignore
+ torch.gcu.empty_cache() # type: ignore
elif str(device).startswith("musa"):
- if torch.musa.is_available():
- torch.musa.empty_cache()
+ if torch.musa.is_available(): # type: ignore
+ torch.musa.empty_cache() # type: ignore
elif str(device).startswith("mlu"):
- if torch.mlu.is_available():
- torch.mlu.empty_cache()
+ if torch.mlu.is_available(): # type: ignore
+ torch.mlu.empty_cache() # type: ignore
elif str(device).startswith("sdaa"):
- if torch.sdaa.is_available():
- torch.sdaa.empty_cache()
+ if torch.sdaa.is_available(): # type: ignore
+ torch.sdaa.empty_cache() # type: ignore
gc.collect()
@@ -240,22 +240,22 @@ def get_vram(device: str) -> int:
# 环境变量未配置或配置错误,根据device自动获取
total_memory = 1
- if torch.cuda.is_available() and str(device).startswith("cuda"):
- total_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024**3)) # 将字节转换为 GB
+ if torch.cuda.is_available() and str(device).startswith("cuda"): # type: ignore
+ total_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 将字节转换为 GB
elif str(device).startswith("npu"):
- if torch_npu.npu.is_available():
- total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3)) # 转为 GB
+ if torch_npu.npu.is_available(): # type: ignore
+ total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
elif str(device).startswith("gcu"):
- if torch.gcu.is_available():
- total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024**3)) # 转为 GB
+ if torch.gcu.is_available(): # type: ignore
+ total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
elif str(device).startswith("musa"):
- if torch.musa.is_available():
- total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024**3)) # 转为 GB
+ if torch.musa.is_available(): # type: ignore
+ total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
elif str(device).startswith("mlu"):
- if torch.mlu.is_available():
- total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024**3)) # 转为 GB
+ if torch.mlu.is_available(): # type: ignore
+ total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
elif str(device).startswith("sdaa"):
- if torch.sdaa.is_available():
- total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024**3)) # 转为 GB
+ if torch.sdaa.is_available(): # type: ignore
+ total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 转为 GB
return total_memory
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 486e3395..fa069dbb 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import os
+from typing import Any
import pypdfium2 as pdfium
from PIL import Image
@@ -121,11 +122,11 @@ class PDFDocument:
# Text
# ------------------------------------------------------------------ #
- def get_page_chars(self, page_idx: int) -> dict:
+ def get_page_chars(self, page_idx: int) -> dict[str, Any]:
page = self._get_page(page_idx)
return get_page_chars(page)
- def get_page_lines(self, page_idx: int) -> list[dict]:
+ def get_page_lines(self, page_idx: int) -> list[dict[str, Any]]:
chars_dict = self.get_page_chars(page_idx)
return get_lines_from_chars(chars_dict["chars"])
@@ -136,7 +137,7 @@ class PDFDocument:
def classify(self) -> str:
return classify(self._pdf_bytes)
- def get_text_quality(self) -> dict:
+ def get_text_quality(self) -> dict[str, Any]:
doc = self._ensure_open()
page_indices = list(range(self.page_count))
return get_text_quality_signal_pdfium(doc, page_indices)
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 0fc26004..13669279 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -10,7 +10,7 @@ import time
from concurrent.futures import ALL_COMPLETED, ProcessPoolExecutor, wait
from concurrent.futures.process import BrokenProcessPool
from io import BytesIO
-from typing import Any, Callable
+from typing import Any, Callable, Literal
import numpy as np
import pypdfium2 as pdfium
@@ -51,7 +51,7 @@ _pdf_render_spawn_submit_count = 0
def pdf_page_to_image(
page: pdfium.PdfPage,
dpi: int = DEFAULT_PDF_IMAGE_DPI,
- image_type: ImageType = ImageType.PIL,
+ image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
) -> dict[str, Any]:
"""Convert pdfium.PdfDocument to image, Then convert the image to base64.
@@ -79,7 +79,11 @@ def pdf_page_to_image(
def _load_images_from_pdf_worker(
- pdf_bytes: bytes, dpi: int, start_page_id: int, end_page_id: int, image_type: ImageType
+ pdf_bytes: bytes,
+ dpi: int,
+ start_page_id: int,
+ end_page_id: int,
+ image_type: Literal["pil_img", "base64_img"],
) -> list[dict[str, Any]]:
"""用于进程池的包装函数"""
return load_images_from_pdf_core(pdf_bytes, dpi, start_page_id, end_page_id, image_type)
@@ -260,7 +264,7 @@ def _load_images_from_pdf_bytes_range(
dpi: int = DEFAULT_PDF_IMAGE_DPI,
start_page_id: int = 0,
end_page_id: int = 0,
- image_type: ImageType = ImageType.PIL,
+ image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
timeout: int | None = None,
threads: int | None = None,
) -> list[dict[str, Any]]:
@@ -341,7 +345,7 @@ async def aio_load_images_from_pdf_bytes_range(
dpi: int = DEFAULT_PDF_IMAGE_DPI,
start_page_id: int = 0,
end_page_id: int = 0,
- image_type: ImageType = ImageType.PIL,
+ image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
timeout: int | None = None,
threads: int | None = None,
) -> list[dict[str, Any]]:
@@ -409,7 +413,7 @@ def load_images_from_pdf_core(
dpi: int = DEFAULT_PDF_IMAGE_DPI,
start_page_id: int = 0,
end_page_id: int | None = None,
- image_type: ImageType = ImageType.PIL, # PIL or BASE64
+ image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
) -> list[dict[str, Any]]:
images_list = []
pdf_doc = None
@@ -439,7 +443,7 @@ def load_images_from_pdf_doc(
dpi: int = DEFAULT_PDF_IMAGE_DPI,
start_page_id: int = 0,
end_page_id: int | None = None,
- image_type: ImageType = ImageType.PIL,
+ image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
pdf_bytes: bytes | None = None,
timeout: int | None = None,
threads: int | None = None,
diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.py
index f3bb9887..2a8eab00 100644
--- a/mineru/utils/title_level_postprocess.py
+++ b/mineru/utils/title_level_postprocess.py
@@ -7,6 +7,7 @@ from typing import Any
from loguru import logger
+from ..types import PageInfo
from .config_reader import get_llm_aided_config
from .llm_aided import llm_aided_title
@@ -24,7 +25,7 @@ def _resolve_title_aided_config() -> dict[str, Any] | None:
return deepcopy(title_aided_config)
-def apply_title_leveling_to_pdf_info(pdf_info: list[dict[str, Any]]) -> None:
+def apply_title_leveling_to_pdf_info(pdf_info: list[PageInfo]) -> None:
title_aided_config = _resolve_title_aided_config()
if title_aided_config:
start_time = time.perf_counter()
@@ -43,20 +44,22 @@ def finalize_client_side_middle_json(middle_json: dict[str, Any]) -> dict[str, A
if not isinstance(middle_json, dict):
raise ValueError("middle_json must be a dict.")
- backend = middle_json.get("_backend")
- pdf_info = middle_json.get("pdf_info")
+ from ..parser.parse_result import ParseResult
+
+ result = ParseResult.from_dict(middle_json)
+ backend = result._backend
if backend == "pipeline":
from mineru.backend.pipeline.model_output_to_middle_json import finalize_middle_json_from_preproc
- finalize_middle_json_from_preproc(pdf_info)
+ finalize_middle_json_from_preproc(result.pages)
elif backend == "vlm":
from mineru.backend.vlm.model_output_to_middle_json import finalize_middle_json
- finalize_middle_json(pdf_info)
+ finalize_middle_json(result.pages)
elif backend == "hybrid":
from mineru.backend.hybrid.model_output_to_middle_json import finalize_middle_json_from_preproc
- finalize_middle_json_from_preproc(pdf_info)
+ finalize_middle_json_from_preproc(result.pages)
return middle_json