Skip to content

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

refactor: add type hints, promote index/guess_lang to Block fields, fix bare list/dict annotations

jinzhenjfc9eb786a1f9
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 00adfda9..e18802e2 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import pypdfium2
+
def extract_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> str:
"""Extract plain text from a PDF file using pypdfium2.
@@ -14,7 +16,6 @@ def extract_text(filepath: str, start_page: int = 0, end_page: int | None = None
Returns:
Extracted text as a string, one page per `\\n\\n`.
"""
- import pypdfium2
pdf = pypdfium2.PdfDocument(filepath)
try:
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index fe85479f..570402ce 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -1,62 +1,60 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import asyncio
import os
import time
from collections import defaultdict
+from typing import Any
import cv2
import numpy as np
import pypdfium2 as pdfium
from loguru import logger
from mineru_vl_utils import MinerUClient
-from mineru_vl_utils.structs import BlockType
+from mineru_vl_utils.structs import BlockType, ExtractResult
+from PIL import Image
from tqdm import tqdm
-from mineru.backend.hybrid.model_output_to_middle_json import (
- apply_server_side_postprocess,
- blocks_to_page_info,
- finalize_middle_json,
- init_middle_json,
+from ...data.data_reader_writer import DataWriter
+from ...utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
+from ...utils.config_reader import get_device, get_processing_window_size
+from ...utils.enum_class import BlockType as MineruBlockType
+from ...utils.enum_class import ImageType, NotExtractType
+from ...utils.model_utils import clean_memory, crop_img, get_vram
+from ...utils.ocr_utils import (
+ OcrConfidence,
+ get_adjusted_mfdetrec_res,
+ get_ocr_result_list,
+ merge_det_boxes,
+ sorted_boxes,
+ update_det_boxes,
)
-from mineru.backend.pipeline.model_init import (
+from ...utils.pdf_classify import classify
+from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_doc
+from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ..pipeline.model_init import (
HybridModelSingleton,
+ MineruHybridModel,
run_layout_inference,
run_mfr_inference,
run_ocr_det_inference,
run_ocr_rec_inference,
)
-from mineru.backend.utils.middle_json_utils import append_pages
-from mineru.backend.utils.runtime_utils import exclude_progress_bar_idle_time
-from mineru.backend.vlm.vlm_analyze import (
+from ..utils.middle_json_utils import append_pages
+from ..utils.runtime_utils import exclude_progress_bar_idle_time
+from ..vlm.vlm_analyze import (
ModelSingleton,
_get_model_async,
_maybe_enable_serial_execution,
aio_predictor_execution_guard,
predictor_execution_guard,
)
-from mineru.data.data_reader_writer import DataWriter
-from mineru.utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
-from mineru.utils.config_reader import get_device, get_processing_window_size
-from mineru.utils.enum_class import BlockType as MineruBlockType
-from mineru.utils.enum_class import ImageType, NotExtractType
-from mineru.utils.model_utils import clean_memory, crop_img, get_vram
-from mineru.utils.ocr_utils import (
- OcrConfidence,
- get_adjusted_mfdetrec_res,
- get_ocr_result_list,
- merge_det_boxes,
- sorted_boxes,
- update_det_boxes,
-)
-from mineru.utils.pdf_classify import classify
-from mineru.utils.pdf_image_tools import (
- aio_load_images_from_pdf_bytes_range,
- load_images_from_pdf_doc,
-)
-from mineru.utils.pdfium_guard import (
- close_pdfium_document,
- get_pdfium_document_page_count,
- open_pdfium_document,
+from .model_output_to_middle_json import (
+ apply_server_side_postprocess,
+ blocks_to_page_info,
+ finalize_middle_json,
+ init_middle_json,
)
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # 让mps可以fallback
@@ -70,7 +68,7 @@ not_extract_list = [item.value for item in NotExtractType]
HYBRID_OCR_DET_TEXT_TYPES = set(not_extract_list)
-def _is_hybrid_ocr_det_candidate(block: dict) -> bool:
+def _is_hybrid_ocr_det_candidate(block: dict[str, Any]) -> bool:
"""判断 Hybrid 文本类块是否需要 OCR det 生成行级视觉信息。"""
return (block.get("type") or block.get("label")) in HYBRID_OCR_DET_TEXT_TYPES
@@ -90,20 +88,20 @@ def ocr_classify(
def ocr_det(
- hybrid_pipeline_model: Any,
- np_images: list,
- model_list: list,
- mfd_res: list,
- _ocr_enable: bool,
- batch_ratio: int = 1,
- *,
- fill_text: bool = True,
- ) -> None:
- def _set_temp_pixel_bbox(res: dict, pixel_bbox: list[int]) -> None:
+ hybrid_pipeline_model: Any,
+ np_images: list[Any],
+ model_list: list[list[dict[str, Any]]],
+ mfd_res: list[Any],
+ _ocr_enable: bool,
+ batch_ratio: int = 1,
+ *,
+ fill_text: bool = True,
+) -> None:
+ def _set_temp_pixel_bbox(res: dict[str, Any], pixel_bbox: list[int]) -> None:
res["_normalized_bbox"] = list(res["bbox"])
res["bbox"] = pixel_bbox
- def _restore_normalized_bbox(res: dict) -> None:
+ def _restore_normalized_bbox(res: dict[str, Any]) -> None:
normalized_bbox = res.pop("_normalized_bbox", None)
if normalized_bbox is not None:
res["bbox"] = normalized_bbox
@@ -236,7 +234,7 @@ def ocr_det(
return ocr_res_list
-def mask_image_regions(np_images: list, model_list: list) -> list:
+def mask_image_regions(np_images: list[Any], model_list: list[list[dict[str, Any]]]) -> list[Any]:
# 根据vlm返回的结果,在每一页中将image、table、equation块mask成白色背景图像
for np_image, vlm_page_results in zip(np_images, model_list):
img_height, img_width = np_image.shape[:2]
@@ -259,7 +257,7 @@ def mask_image_regions(np_images: list, model_list: list) -> list:
return np_images
-def normalize_bbox_to_unit(item: dict, page_width: int, page_height: int) -> None:
+def normalize_bbox_to_unit(item: dict[str, Any], page_width: int, page_height: int) -> bool:
"""将像素级bbox归一化为[0, 1]区间"""
bbox = item.get("bbox")
if bbox is None or len(bbox) != 4:
@@ -279,15 +277,14 @@ def normalize_bbox_to_unit(item: dict, page_width: int, page_height: int) -> Non
return True
-def _formula_item_to_pixel_bbox(item: dict) -> list[int]:
+def _formula_item_to_pixel_bbox(item: dict[str, Any]) -> list[int] | None:
bbox = item.get("bbox")
if bbox is not None and len(bbox) == 4:
return [int(float(v)) for v in bbox]
-
return None
-def _build_inline_formula_inputs(images_layout_res: list) -> list:
+def _build_inline_formula_inputs(images_layout_res: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
inline_formula_inputs = []
for layout_res in images_layout_res:
page_inline_formula_inputs = []
@@ -309,7 +306,7 @@ def _build_inline_formula_inputs(images_layout_res: list) -> list:
return inline_formula_inputs
-def _build_formula_mask_inputs(images_layout_res: list) -> list:
+def _build_formula_mask_inputs(images_layout_res: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""从 layout 检测结果提取公式框,供 OCR det 规避行内/行间公式区域。"""
page_formula_masks = []
for layout_res in images_layout_res:
@@ -354,7 +351,7 @@ def _bbox_to_pixel_bbox(bbox: list[float], page_size: list[int]) -> list[int]:
return [left, top, right, bottom]
-def _collect_layout_doc_title_bboxes(layout_res: list, page_size: list[int]) -> list[list[float]]:
+def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: list[int]) -> list[list[float]]:
"""只收集layout小模型输出的doc_title框,忽略paragraph_title等其他类型。"""
doc_title_bboxes = []
for layout_item in layout_res or []:
@@ -375,11 +372,11 @@ def _has_doc_title_overlap(title_bbox: list[float], doc_title_bboxes: list[list[
def _apply_layout_title_split(
- model_list,
- images_layout_res,
- page_sizes,
- overlap_threshold=LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,
-):
+ model_list: list[list[dict[str, object]]],
+ images_layout_res: list[list[dict[str, object]]],
+ page_sizes: list[tuple[int, int]],
+ overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,
+) -> None:
"""用layout doc_title框将VLM title拆分为doc_title和paragraph_title。"""
for page_model_list, layout_res, page_size in zip(model_list, images_layout_res, page_sizes):
doc_title_bboxes = _collect_layout_doc_title_bboxes(layout_res, page_size)
@@ -396,10 +393,10 @@ def _apply_layout_title_split(
def _predict_layout_for_title_split(
- hybrid_pipeline_model,
- images,
- batch_ratio,
-):
+ hybrid_pipeline_model: MineruHybridModel,
+ images: list[Image.Image],
+ batch_ratio: int,
+) -> list[dict[str, object]]:
"""执行layout小模型检测,专门为Hybrid标题拆分提供页面layout结果。"""
return run_layout_inference(
hybrid_pipeline_model.layout_model.batch_predict,
@@ -409,13 +406,13 @@ def _predict_layout_for_title_split(
def _process_ocr_and_formulas(
- images_pil_list,
- model_list,
- language,
- inline_formula_enable,
- _ocr_enable,
+ images_pil_list: list[Image.Image],
+ model_list: list[ExtractResult],
+ language: str | None,
+ inline_formula_enable: bool,
+ _ocr_enable: bool,
batch_ratio: int = 1,
-):
+) -> tuple[list[list[dict[str, object]]], MineruHybridModel]:
"""处理OCR和公式识别"""
# 遍历model_list,对文本块截图交由OCR识别
@@ -572,11 +569,11 @@ def _process_ocr_and_formulas(
def _apply_layout_title_split_for_window(
- images_pil_list,
- model_list,
- language,
- batch_ratio,
-):
+ images_pil_list: list[Image.Image],
+ model_list: list[ExtractResult],
+ language: str | None,
+ batch_ratio: int,
+) -> None:
"""为VLM-OCR路径补跑layout小模型,先基于VLM原始title做OCR det,再拆分标题。"""
hybrid_model_singleton = HybridModelSingleton()
hybrid_pipeline_model = hybrid_model_singleton.get_model(
@@ -614,10 +611,10 @@ def _apply_layout_title_split_for_window(
def _normalize_bbox(
- inline_formula_list,
- ocr_res_list,
- images_pil_list,
-):
+ inline_formula_list: list[list[dict[str, object]]],
+ ocr_res_list: list[list[dict[str, object]]],
+ images_pil_list: list[Image.Image],
+) -> None:
"""归一化坐标并生成最终结果"""
for page_inline_formula_list, page_ocr_res_list, page_pil_image in zip(inline_formula_list, ocr_res_list, images_pil_list):
if page_inline_formula_list or page_ocr_res_list:
@@ -630,7 +627,7 @@ def _normalize_bbox(
normalize_bbox_to_unit(ocr_res, page_width, page_height)
-def _build_inline_formula_model_item(formula: dict) -> dict:
+def _build_inline_formula_model_item(formula: dict[str, Any]) -> dict[str, Any]:
return {
"type": "inline_formula",
"bbox": list(formula["bbox"]),
@@ -639,7 +636,7 @@ def _build_inline_formula_model_item(formula: dict) -> dict:
}
-def _build_ocr_text_model_item(ocr_res: dict, keep_text: bool = True) -> dict:
+def _build_ocr_text_model_item(ocr_res: dict[str, Any], keep_text: bool = True) -> dict[str, Any]:
"""构造 OCR det sidecar;VLM-OCR 路径可只保留空文本行提示。"""
return {
"type": "ocr_text",
@@ -650,11 +647,11 @@ def _build_ocr_text_model_item(ocr_res: dict, keep_text: bool = True) -> dict:
def _merge_page_sidecar_items(
- model_list,
- inline_formula_list,
- ocr_res_list,
- keep_ocr_text=True,
-):
+ model_list: list[list[dict[str, object]]],
+ inline_formula_list: list[list[dict[str, object]]],
+ ocr_res_list: list[list[dict[str, object]]],
+ keep_ocr_text: bool = True,
+) -> list[list[dict[str, object]]]:
merged_model_list = []
for page_model_list, page_inline_formula_list, page_ocr_res_list in zip(model_list, inline_formula_list, ocr_res_list):
merged_page_model_list = list(page_model_list)
@@ -670,7 +667,7 @@ def _merge_page_sidecar_items(
return merged_model_list
-def get_batch_ratio(device):
+def get_batch_ratio(device: str) -> int:
"""
根据显存大小或环境变量获取 batch ratio
"""
@@ -726,7 +723,7 @@ def _should_enable_vlm_ocr(ocr_enable: bool, language: str, inline_formula_enabl
return ocr_enable and language in ["ch", "en"] and inline_formula_enable and not force_pipeline
-def _close_images(images_list: list) -> None:
+def _close_images(images_list: list[dict[str, Any]]) -> None:
for image_dict in images_list or []:
pil_img = image_dict.get("img_pil")
if pil_img is not None:
@@ -737,18 +734,18 @@ def _close_images(images_list: list) -> None:
def doc_analyze(
- pdf_bytes,
+ pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend="transformers",
+ backend: str = "transformers",
parse_method: str = "auto",
language: str = "ch",
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
- **kwargs,
-):
+ **kwargs: object,
+) -> tuple[dict[str, object], list[list[dict[str, object]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
if predictor is None:
predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
@@ -760,7 +757,7 @@ def doc_analyze(
pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
middle_json = init_middle_json(_ocr_enable, _vlm_ocr_enable)
- model_list = []
+ model_list: list[ExtractResult] = []
doc_closed = False
hybrid_pipeline_model = None
try:
@@ -881,18 +878,18 @@ def doc_analyze(
async def aio_doc_analyze(
- pdf_bytes,
+ pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend="transformers",
+ backend: str = "transformers",
parse_method: str = "auto",
language: str = "ch",
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
- **kwargs,
-):
+ **kwargs: object,
+) -> tuple[dict[str, object], list[list[dict[str, object]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
if predictor is None:
predictor = await _get_model_async(backend, model_path, server_url, **kwargs)
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index dd9dc779..463b0680 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -1,16 +1,19 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import copy
import re
from loguru import logger
-
-from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
-from mineru.utils.enum_class import ContentType, BlockType, NotExtractType
-from mineru.utils.guess_suffix_or_lang import guess_language_by_text
-from mineru.types import Block, Line, Span
-from mineru.utils.span_block_fix import fix_text_block
-from mineru.utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
-from mineru.utils.visual_magic_model_utils import (
+from PIL import Image
+
+from ...types import Block, Line, Span
+from ...utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from ...utils.enum_class import BlockType, ContentType, NotExtractType
+from ...utils.guess_suffix_or_lang import guess_language_by_text
+from ...utils.span_block_fix import fix_text_block
+from ...utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
+from ...utils.visual_magic_model_utils import (
GENERIC_CHILD_TYPES,
IMAGE_BLOCK_BODY,
VISUAL_MAIN_TYPES,
@@ -21,6 +24,7 @@ from mineru.utils.visual_magic_model_utils import (
isolated_formula_clean,
regroup_visual_blocks,
)
+
not_extract_list = [item.value for item in NotExtractType] + [
BlockType.CAPTION,
BlockType.FOOTNOTE,
@@ -40,7 +44,7 @@ OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {
}
-def _copy_raw_text_block_metadata(raw_block_type, block_info, block):
+def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, object], block: Block) -> None:
if raw_block_type != BlockType.TEXT:
return
if "merge_prev" in block_info:
@@ -50,15 +54,15 @@ def _copy_raw_text_block_metadata(raw_block_type, block_info, block):
class MagicModel:
def __init__(
self,
- page_model_list: list,
- page,
- scale,
- page_pil_img,
- width,
- height,
- _ocr_enable,
- _vlm_ocr_enable,
- ):
+ page_model_list: list[dict[str, object]],
+ page: object,
+ scale: float,
+ page_pil_img: Image.Image,
+ width: int,
+ height: int,
+ _ocr_enable: bool,
+ _vlm_ocr_enable: bool,
+ ) -> None:
(
self.page_blocks,
self.page_inline_formula,
@@ -76,20 +80,24 @@ class MagicModel:
inline_formula["bbox"] = list(self.cal_real_bbox(inline_formula["bbox"]))
inline_formula_latex = inline_formula.pop("latex", "")
if inline_formula_latex:
- page_text_inline_formula_spans.append(Span(
- type=ContentType.INLINE_EQUATION,
- bbox=inline_formula["bbox"],
- content=inline_formula_latex,
- score=inline_formula["score"],
- ))
+ page_text_inline_formula_spans.append(
+ Span(
+ type=ContentType.INLINE_EQUATION,
+ bbox=inline_formula["bbox"],
+ content=inline_formula_latex,
+ score=inline_formula["score"],
+ )
+ )
for ocr_res in self.page_ocr_res:
ocr_res["bbox"] = list(self.cal_real_bbox(ocr_res["bbox"]))
- page_text_inline_formula_spans.append(Span(
- type=ContentType.TEXT,
- bbox=ocr_res["bbox"],
- content=ocr_res.get("text", ""),
- score=ocr_res["score"],
- ))
+ page_text_inline_formula_spans.append(
+ Span(
+ type=ContentType.TEXT,
+ bbox=ocr_res["bbox"],
+ content=ocr_res.get("text", ""),
+ score=ocr_res["score"],
+ )
+ )
if not _vlm_ocr_enable and not _ocr_enable:
virtual_block = [0, 0, width, height, None, None, None, "text"]
page_text_inline_formula_spans = txt_spans_extract(
@@ -110,11 +118,7 @@ class MagicModel:
raw_block_type = block_type
block_content = block_info.get("content")
block_angle = block_info.get("angle", 0)
- block_sub_type = (
- block_info.get("sub_type")
- if raw_block_type in ["image", "chart"]
- else None
- )
+ block_sub_type = block_info.get("sub_type") if raw_block_type in ["image", "chart"] else None
except Exception as e:
# 如果解析失败,可能是因为格式不正确,跳过这个块
logger.warning(f"Invalid block format: {block_info}, error: {e}")
@@ -178,12 +182,13 @@ class MagicModel:
if span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:
span = Span(type=span_type, bbox=block_bbox)
if span_type == ContentType.TABLE:
- span["html"] = block_content
+ span.html = block_content
elif raw_block_type in ["image", "chart"] and block_content is not None:
- span["content"] = block_content
+ span.content = block_content
elif span_type == ContentType.INTERLINE_EQUATION:
span = Span(
- type=span_type, bbox=block_bbox,
+ type=span_type,
+ bbox=block_bbox,
content=isolated_formula_clean(block_content),
)
elif _vlm_ocr_enable or block_type not in not_extract_list:
@@ -210,31 +215,41 @@ class MagicModel:
if start > last_end:
text_before = block_content[last_end:start]
if text_before.strip():
- spans.append(Span(
- type=ContentType.TEXT, bbox=block_bbox,
- content=text_before,
- ))
+ spans.append(
+ Span(
+ type=ContentType.TEXT,
+ bbox=block_bbox,
+ content=text_before,
+ )
+ )
formula = match.group(1)
- spans.append(Span(
- type=ContentType.INLINE_EQUATION, bbox=block_bbox,
- content=formula.strip(),
- ))
+ spans.append(
+ Span(
+ type=ContentType.INLINE_EQUATION,
+ bbox=block_bbox,
+ content=formula.strip(),
+ )
+ )
last_end = end
if last_end < len(block_content):
text_after = block_content[last_end:]
if text_after.strip():
- spans.append(Span(
- type=ContentType.TEXT, bbox=block_bbox,
- content=text_after,
- ))
+ spans.append(
+ Span(
+ type=ContentType.TEXT,
+ bbox=block_bbox,
+ content=text_after,
+ )
+ )
span = spans
else:
span = Span(
- type=span_type, bbox=block_bbox,
+ type=span_type,
+ bbox=block_bbox,
content=block_content,
)
@@ -253,19 +268,15 @@ class MagicModel:
self.all_spans.extend(span)
spans = span
else:
- raise ValueError(
- f"Invalid span type: {span_type}, expected dict or list, got {type(span)}"
- )
+ raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")
if block_type == BlockType.CODE_BODY:
if switch_code_to_algorithm and code_block_sub_type == "code":
code_block_sub_type = "algorithm"
- line = Line(spans=spans)
- line["bbox"] = block_bbox
+ line = Line(spans=spans, bbox=block_bbox)
line["extra"] = {"type": code_block_sub_type, "guess_lang": guess_lang}
else:
- line = Line(spans=spans)
- line["bbox"] = block_bbox
+ line = Line(spans=spans, bbox=block_bbox)
block = Block(type=block_type, bbox=block_bbox, lines=[line])
block["angle"] = block_angle
@@ -275,9 +286,7 @@ class MagicModel:
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)
- )
+ 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
_copy_raw_text_block_metadata(raw_block_type, block_info, block)
@@ -369,7 +378,9 @@ class MagicModel:
self.text_blocks.append(block)
@staticmethod
- def _split_page_model_list(page_model_list):
+ def _split_page_model_list(
+ page_model_list: list[dict[str, object]],
+ ) -> tuple[list[dict[str, object]], list[dict[str, object]], list[dict[str, object]]]:
page_blocks = []
page_inline_formula = []
page_ocr_res = []
@@ -386,12 +397,12 @@ class MagicModel:
return page_blocks, page_inline_formula, page_ocr_res
@staticmethod
- def _supports_ocr_det_lines(block_type):
+ def _supports_ocr_det_lines(block_type: str) -> bool:
"""判断当前块类型是否需要保留 OCR det 行提示供 Hybrid 段落合并使用。"""
return block_type in OCR_DET_LINE_BLOCK_TYPES
@staticmethod
- def _build_ocr_det_lines(block_spans):
+ def _build_ocr_det_lines(block_spans: list[Span]) -> list[Line]:
"""将 OCR det span 聚合成 line,但不改变 VLM-OCR 的 canonical 文本内容。"""
if not block_spans:
return []
@@ -399,7 +410,7 @@ class MagicModel:
hint_block = {"spans": copy.deepcopy(block_spans)}
return fix_text_block(hint_block).get("lines", [])
- def cal_real_bbox(self, bbox):
+ def cal_real_bbox(self, bbox: list[float]) -> tuple[int, int, int, int]:
x1, y1, x2, y2 = bbox
x_1, y_1, x_2, y_2 = (
int(x1 * self.width),
@@ -413,42 +424,46 @@ class MagicModel:
y_1, y_2 = y_2, y_1
return (x_1, y_1, x_2, y_2)
- def get_list_blocks(self):
+ def get_list_blocks(self) -> list[Block]:
return self.list_blocks
- def get_image_blocks(self):
+ def get_image_blocks(self) -> list[Block]:
return self.image_blocks
- def get_table_blocks(self):
+ def get_table_blocks(self) -> list[Block]:
return self.table_blocks
- def get_chart_blocks(self):
+ def get_chart_blocks(self) -> list[Block]:
return self.chart_blocks
- def get_code_blocks(self):
+ def get_code_blocks(self) -> list[Block]:
return self.code_blocks
- def get_ref_text_blocks(self):
+ def get_ref_text_blocks(self) -> list[Block]:
return self.ref_text_blocks
- def get_phonetic_blocks(self):
+ def get_phonetic_blocks(self) -> list[Block]:
return self.phonetic_blocks
- def get_title_blocks(self):
+ def get_title_blocks(self) -> list[Block]:
return self.title_blocks
- def get_text_blocks(self):
+ def get_text_blocks(self) -> list[Block]:
return self.text_blocks
- def get_interline_equation_blocks(self):
+ def get_interline_equation_blocks(self) -> list[Block]:
return self.interline_equation_blocks
- def get_discarded_blocks(self):
+ def get_discarded_blocks(self) -> list[Block]:
return self.discarded_blocks
- def get_all_spans(self):
+ def get_all_spans(self) -> list[Span]:
return self.all_spans
-def fix_list_blocks(list_blocks, text_blocks, ref_text_blocks):
+
+
+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:
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index 296e686e..199ea205 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -1,10 +1,12 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import os
from typing import Any
-from ...types import PageInfo
-
+from ...data.data_reader_writer import DataWriter
+from ...types import Block, PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.cut_image import cut_image_and_table
from ...utils.enum_class import BlockType, ContentType
@@ -12,7 +14,9 @@ from ...utils.hash_utils import bytes_md5
from ...utils.pdfium_guard import pdfium_guard
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ...version import __version__
+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,
@@ -23,7 +27,7 @@ from ..utils.runtime_utils import cross_page_table_merge
from .hybrid_magic_model import MagicModel
-def _resolve_title_line_avg_height(title_block):
+def _resolve_title_line_avg_height(title_block: Block) -> int:
"""解析标题平均行高:优先复用 Hybrid OCR det 行提示,再回退到原始行或块高。"""
for lines_key in [OCR_DET_LINES_KEY, "lines"]:
line_heights = []
@@ -44,10 +48,10 @@ def _resolve_title_line_avg_height(title_block):
def blocks_to_page_info(
- page_model_list: list,
- image_dict: dict,
+ page_model_list: list[dict[str, Any]],
+ image_dict: dict[str, Any],
page: Any,
- image_writer: Any,
+ image_writer: DataWriter,
page_index: int,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
@@ -113,7 +117,6 @@ def blocks_to_page_info(
# 对page_blocks根据index的值进行排序
page_blocks.sort(key=lambda x: x["index"])
-
page_info = PageInfo(
preproc_blocks=page_blocks,
discarded_blocks=discarded_blocks,
@@ -123,13 +126,11 @@ def blocks_to_page_info(
return page_info
-def _apply_post_ocr(pdf_info_list, hybrid_pipeline_model):
- from mineru.backend.utils.middle_json_utils import apply_post_ocr
-
+def _apply_post_ocr(pdf_info_list: list[PageInfo], hybrid_pipeline_model: MineruHybridModel) -> None:
apply_post_ocr(pdf_info_list, hybrid_pipeline_model.ocr_model)
-def _normalize_split_title_blocks(pdf_info_list):
+def _normalize_split_title_blocks(pdf_info_list: list[PageInfo]) -> None:
"""将Hybrid内部拆分标题统一为输出层通用title,并补齐默认标题层级。"""
title_type_to_level = {
BlockType.DOC_TITLE: 1,
@@ -145,7 +146,7 @@ def _normalize_split_title_blocks(pdf_info_list):
block["level"] = title_level
-def init_middle_json(_ocr_enable, _vlm_ocr_enable):
+def init_middle_json(_ocr_enable: bool, _vlm_ocr_enable: bool) -> dict[str, Any]:
return {
"pdf_info": [],
"_backend": "hybrid",
@@ -156,17 +157,17 @@ def init_middle_json(_ocr_enable, _vlm_ocr_enable):
def apply_server_side_postprocess(
- pdf_info_list,
- hybrid_pipeline_model,
- _ocr_enable,
- _vlm_ocr_enable,
-):
+ pdf_info_list: list[PageInfo],
+ hybrid_pipeline_model: MineruHybridModel,
+ _ocr_enable: bool,
+ _vlm_ocr_enable: bool,
+) -> None:
"""执行 Hybrid 只能在服务端完成的 post-OCR,避免客户端依赖 pipeline OCR 模型。"""
if not (_vlm_ocr_enable or _ocr_enable):
_apply_post_ocr(pdf_info_list, hybrid_pipeline_model)
-def finalize_middle_json_from_preproc(pdf_info_list):
+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(
@@ -185,7 +186,7 @@ def finalize_middle_json_from_preproc(pdf_info_list):
def finalize_middle_json(
pdf_info_list: list[PageInfo],
- hybrid_pipeline_model: Any,
+ hybrid_pipeline_model: MineruHybridModel,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
) -> None:
@@ -200,16 +201,14 @@ def finalize_middle_json(
def result_to_middle_json(
- model_list: list,
- images_list: list,
+ model_list: list[list[dict[str, Any]]],
+ images_list: list[dict[str, Any]],
pdf_doc: Any,
- image_writer: Any,
+ image_writer: DataWriter,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
- hybrid_pipeline_model: Any,
-) -> dict:
- from mineru.backend.utils.middle_json_utils import build_middle_json
-
+ hybrid_pipeline_model: MineruHybridModel,
+) -> dict[str, Any]:
return build_middle_json(
model_list,
images_list,
diff --git a/mineru/backend/office/docx_analyze.py b/mineru/backend/office/docx_analyze.py
index 31f6e3e0..7c3950c5 100644
--- a/mineru/backend/office/docx_analyze.py
+++ b/mineru/backend/office/docx_analyze.py
@@ -1,14 +1,16 @@
# Copyright (c) Opendatalab. All rights reserved.
import time
from io import BytesIO
+from typing import Any
from loguru import logger
+from ...data.data_reader_writer import FileBasedDataWriter
from ...model.docx.main import convert_binary
from .model_output_to_middle_json import result_to_middle_json
-def office_docx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
+def office_docx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict[str, Any]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -18,11 +20,7 @@ def office_docx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(
- results,
- image_writer,
- )
-
+ middle_json = result_to_middle_json(results, image_writer)
return middle_json, results
@@ -32,6 +30,7 @@ if __name__ == "__main__":
# module is executed. Allow the user to override the path via a
# command-line argument for even greater flexibility.
import argparse
+ import json
from pathlib import Path
script_root = Path(__file__).resolve().parent.parent.parent.parent
@@ -48,7 +47,6 @@ if __name__ == "__main__":
args = parser.parse_args()
docx_path = Path(args.docx)
- from mineru.data.data_reader_writer import FileBasedDataWriter
with open(docx_path, "rb") as f:
file_bytes = f.read()
@@ -58,6 +56,4 @@ if __name__ == "__main__":
image_writer=image_writer,
)
- import json
-
logger.info(json.dumps(middle_json, indent=2, ensure_ascii=False))
diff --git a/mineru/backend/office/mkcontent/inline_renderer.py b/mineru/backend/office/mkcontent/inline_renderer.py
index f43685cc..d7a8742f 100644
--- a/mineru/backend/office/mkcontent/inline_renderer.py
+++ b/mineru/backend/office/mkcontent/inline_renderer.py
@@ -1,61 +1,60 @@
# Copyright (c) Opendatalab. All rights reserved.
-from dataclasses import dataclass, field
+from __future__ import annotations
+
import unicodedata
+from collections.abc import Generator
+from dataclasses import dataclass, field
from html import escape
+from typing import Any
-from mineru.backend.utils.markdown_utils import (
- escape_conservative_markdown_text,
- escape_text_block_markdown_prefix,
-)
-from mineru.utils.config_reader import get_latex_delimiter_config
-from mineru.utils.enum_class import BlockType, ContentType
+from ....types import Block, Span
+from ....utils.config_reader import get_latex_delimiter_config
+from ....utils.enum_class import BlockType, ContentType
+from ...utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
latex_delimiters_config = get_latex_delimiter_config()
-default_delimiters = {
- 'display': {'left': '$$', 'right': '$$'},
- 'inline': {'left': '$', 'right': '$'}
-}
+default_delimiters = {"display": {"left": "$$", "right": "$$"}, "inline": {"left": "$", "right": "$"}}
delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
-display_left_delimiter = delimiters['display']['left']
-display_right_delimiter = delimiters['display']['right']
-inline_left_delimiter = delimiters['inline']['left']
-inline_right_delimiter = delimiters['inline']['right']
+display_left_delimiter = delimiters["display"]["left"]
+display_right_delimiter = delimiters["display"]["right"]
+inline_left_delimiter = delimiters["inline"]["left"]
+inline_right_delimiter = delimiters["inline"]["right"]
-OFFICE_INLINE_SYNTAX_HTML = 'html'
-OFFICE_INLINE_SYNTAX_MARKDOWN = 'markdown'
+OFFICE_INLINE_SYNTAX_HTML = "html"
+OFFICE_INLINE_SYNTAX_MARKDOWN = "markdown"
OFFICE_MARKDOWN_STYLE_WRAPPERS = {
- frozenset({'bold'}): '**',
- frozenset({'italic'}): '*',
- frozenset({'strikethrough'}): '~~',
- frozenset({'bold', 'italic'}): '***',
+ frozenset({"bold"}): "**",
+ frozenset({"italic"}): "*",
+ frozenset({"strikethrough"}): "~~",
+ frozenset({"bold", "italic"}): "***",
}
OFFICE_COMPLEX_HTML_STYLES = {
- 'underline',
- 'emphasis',
- 'superscript',
- 'subscript',
+ "underline",
+ "emphasis",
+ "superscript",
+ "subscript",
}
-OFFICE_EMPHASIS_STYLE = 'text-emphasis: dot; text-emphasis-position: under;'
+OFFICE_EMPHASIS_STYLE = "text-emphasis: dot; text-emphasis-position: under;"
STYLE_WRAPPER_OPEN = {
- 'emphasis': f'<span style="{OFFICE_EMPHASIS_STYLE}">',
- 'strikethrough': '<s>',
- 'italic': '<em>',
- 'bold': '<strong>',
- 'underline': '<u>',
- 'superscript': '<sup>',
- 'subscript': '<sub>',
+ "emphasis": f'<span style="{OFFICE_EMPHASIS_STYLE}">',
+ "strikethrough": "<s>",
+ "italic": "<em>",
+ "bold": "<strong>",
+ "underline": "<u>",
+ "superscript": "<sup>",
+ "subscript": "<sub>",
}
STYLE_WRAPPER_CLOSE = {
- 'emphasis': '</span>',
- 'strikethrough': '</s>',
- 'italic': '</em>',
- 'bold': '</strong>',
- 'underline': '</u>',
- 'superscript': '</sup>',
- 'subscript': '</sub>',
+ "emphasis": "</span>",
+ "strikethrough": "</s>",
+ "italic": "</em>",
+ "bold": "</strong>",
+ "underline": "</u>",
+ "superscript": "</sup>",
+ "subscript": "</sub>",
}
@@ -65,7 +64,7 @@ class RenderedPart:
span_type: str
rendered_content: str
- raw_content: str = ''
+ raw_content: str = ""
style: list = field(default_factory=list)
has_markdown_wrapper: bool = False
@@ -86,7 +85,7 @@ def _apply_markdown_style(content: str, style: list) -> str:
style_key = _get_markdown_style_key(style)
wrapper = OFFICE_MARKDOWN_STYLE_WRAPPERS.get(style_key)
if wrapper:
- return f'{wrapper}{content}{wrapper}'
+ return f"{wrapper}{content}{wrapper}"
return content
@@ -95,24 +94,24 @@ def _apply_html_style(content: str, style: list) -> str:
if not style or not content:
return content
- if 'superscript' in style:
- content = f'<sup>{content}</sup>'
- elif 'subscript' in style:
- content = f'<sub>{content}</sub>'
+ if "superscript" in style:
+ content = f"<sup>{content}</sup>"
+ elif "subscript" in style:
+ content = f"<sub>{content}</sub>"
- if 'underline' in style:
- content = f'<u>{content}</u>'
+ if "underline" in style:
+ content = f"<u>{content}</u>"
- if 'bold' in style:
- content = f'<strong>{content}</strong>'
+ if "bold" in style:
+ content = f"<strong>{content}</strong>"
- if 'italic' in style:
- content = f'<em>{content}</em>'
+ if "italic" in style:
+ content = f"<em>{content}</em>"
- if 'strikethrough' in style:
- content = f'<s>{content}</s>'
+ if "strikethrough" in style:
+ content = f"<s>{content}</s>"
- if 'emphasis' in style:
+ if "emphasis" in style:
content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'
return content
@@ -128,7 +127,7 @@ def _apply_configured_style(content: str, style: list, inline_syntax: str) -> st
def _render_link(text: str, url: str, inline_syntax: str) -> str:
"""按 block 级语法渲染链接,复杂 HTML block 内统一使用 <a>。"""
if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
- return f'[{text}]({url})'
+ return f"[{text}]({url})"
return f'<a href="{escape(url, quote=True)}">{text}</a>'
@@ -141,16 +140,16 @@ def _escape_office_inline_text(content: str, inline_syntax: str) -> str:
return escape_conservative_markdown_text(escape(content, quote=False))
-def get_title_level(para_block):
- title_level = para_block.get('level', 2)
+def get_title_level(para_block: Block) -> int:
+ title_level = para_block.get("level", 2)
return title_level
def _make_rendered_part(
- span_type,
+ span_type: str,
rendered_content: str,
- raw_content: str = '',
- style: list | None = None,
+ raw_content: str = "",
+ style: list[str] | None = None,
has_markdown_wrapper: bool = False,
) -> RenderedPart:
"""构造段落渲染中间片段,并保留 Markdown 边界补空格所需的原始信息。"""
@@ -163,7 +162,7 @@ def _make_rendered_part(
)
-def _get_first_non_whitespace_char(text: str):
+def _get_first_non_whitespace_char(text: str) -> str | None:
"""返回文本中第一个非空白字符,用于 block 级 Markdown 风险判定。"""
for ch in text:
if not ch.isspace():
@@ -171,7 +170,7 @@ def _get_first_non_whitespace_char(text: str):
return None
-def _get_last_non_whitespace_char(text: str):
+def _get_last_non_whitespace_char(text: str) -> str | None:
"""返回文本中最后一个非空白字符,用于 block 级 Markdown 风险判定。"""
for ch in reversed(text):
if not ch.isspace():
@@ -181,7 +180,7 @@ def _get_last_non_whitespace_char(text: str):
def _is_punctuation_or_symbol(ch: str) -> bool:
"""判断字符是否属于 Unicode 标点或符号类别。"""
- return unicodedata.category(ch).startswith(('P', 'S'))
+ return unicodedata.category(ch).startswith(("P", "S"))
def _is_boundary_text_char(ch: str) -> bool:
@@ -232,19 +231,19 @@ def _join_rendered_parts(parts: list[RenderedPart]) -> str:
is_last = i == len(parts) - 1
if span_type == ContentType.INLINE_EQUATION:
- if rendered_parts and not rendered_parts[-1].endswith(' '):
- rendered_parts.append(' ')
+ if rendered_parts and not rendered_parts[-1].endswith(" "):
+ rendered_parts.append(" ")
rendered_parts.append(content)
if not is_last:
- rendered_parts.append(' ')
+ rendered_parts.append(" ")
else:
if prev_part is not None and _needs_markdown_boundary_space(prev_part, part):
- rendered_parts.append(' ')
+ rendered_parts.append(" ")
rendered_parts.append(content)
prev_part = part
- return ''.join(rendered_parts)
+ return "".join(rendered_parts)
def _strip_text_block_markdown_edges(content: str) -> str:
@@ -258,16 +257,16 @@ def _get_visible_space_marker(style: list) -> str | None:
"""根据可见空格样式选择 Markdown marker,下划线优先于删除线。"""
if not style:
return None
- if 'underline' in style:
- return '_'
- if 'strikethrough' in style:
- return '-'
+ if "underline" in style:
+ return "_"
+ if "strikethrough" in style:
+ return "-"
return None
def _is_ascii_space_only(content: str) -> bool:
"""判断文本是否只由普通 ASCII 空格组成。"""
- return bool(content) and all(char == ' ' for char in content)
+ return bool(content) and all(char == " " for char in content)
def _replace_ascii_spaces_with_marker(
@@ -279,22 +278,20 @@ def _replace_ascii_spaces_with_marker(
rendered_parts = []
text_buffer = []
- def flush_text_buffer():
+ def flush_text_buffer() -> None:
if text_buffer:
- rendered_parts.append(
- _escape_office_inline_text(''.join(text_buffer), inline_syntax)
- )
+ rendered_parts.append(_escape_office_inline_text("".join(text_buffer), inline_syntax))
text_buffer.clear()
for char in content:
- if char == ' ':
+ if char == " ":
flush_text_buffer()
rendered_parts.append(marker)
else:
text_buffer.append(char)
flush_text_buffer()
- return ''.join(rendered_parts)
+ return "".join(rendered_parts)
def _render_text_with_edge_space_markers(
@@ -303,15 +300,11 @@ def _render_text_with_edge_space_markers(
inline_syntax: str,
) -> str:
"""渲染非空文本:只把首尾 ASCII 空格转成 marker,中间普通空格保持原样。"""
- leading_space_count = len(content) - len(content.lstrip(' '))
- trailing_space_count = len(content) - len(content.rstrip(' '))
+ leading_space_count = len(content) - len(content.lstrip(" "))
+ trailing_space_count = len(content) - len(content.rstrip(" "))
text_end = len(content) - trailing_space_count if trailing_space_count else len(content)
core_text = content[leading_space_count:text_end]
- return (
- marker * leading_space_count
- + _escape_office_inline_text(core_text, inline_syntax)
- + marker * trailing_space_count
- )
+ return marker * leading_space_count + _escape_office_inline_text(core_text, inline_syntax) + marker * trailing_space_count
def _render_visible_space_marker_text(
@@ -331,7 +324,7 @@ def _render_visible_space_marker_text(
)
style = style or []
- if marker == '-' and not _is_ascii_space_only(content):
+ if marker == "-" and not _is_ascii_space_only(content):
return _apply_configured_style(
_render_text_with_edge_space_markers(content, marker, inline_syntax),
render_style,
@@ -344,7 +337,7 @@ def _render_visible_space_marker_text(
marker,
inline_syntax,
)
- ignored_style = 'underline' if marker == '_' else 'strikethrough'
+ ignored_style = "underline" if marker == "_" else "strikethrough"
render_style = [name for name in (render_style or []) if name != ignored_style]
return _apply_configured_style(rendered_content, render_style, inline_syntax)
@@ -367,20 +360,20 @@ def _render_styled_inline_text(content: str, style: list, inline_syntax: str) ->
def _escape_standalone_marker_rule(content: str) -> str:
"""独立一行全是 marker 时转义首个字符,避免被 Markdown 当作分隔线。"""
- if content and all(char == '_' for char in content):
- return f'\\{content}'
- if content and all(char == '-' for char in content):
- return f'\\{content}'
+ if content and all(char == "_" for char in content):
+ return f"\\{content}"
+ if content and all(char == "-" for char in content):
+ return f"\\{content}"
return content
def _append_text_part(
parts: list[RenderedPart],
original_content: str,
- span_style: list,
+ span_style: list[str],
inline_syntax: str,
- render_style: list | None = None,
-):
+ render_style: list[str] | None = None,
+) -> None:
render_style = span_style if render_style is None else render_style
if original_content and _get_visible_space_marker(span_style):
parts.append(
@@ -407,10 +400,8 @@ def _append_text_part(
render_style,
inline_syntax,
)
- leading = escaped_content[
- :len(escaped_content) - len(escaped_content.lstrip())
- ]
- trailing = escaped_content[len(escaped_content.rstrip()):]
+ leading = escaped_content[: len(escaped_content) - len(escaped_content.lstrip())]
+ trailing = escaped_content[len(escaped_content.rstrip()) :]
parts.append(
_make_rendered_part(
ContentType.TEXT,
@@ -421,7 +412,7 @@ def _append_text_part(
)
)
elif original_content:
- visible_styles = {'underline', 'strikethrough'}
+ visible_styles = {"underline", "strikethrough"}
rendered_content = original_content
if span_style and any(s in visible_styles for s in span_style):
rendered_content = _apply_configured_style(
@@ -446,9 +437,9 @@ def _split_plain_blank_edges(
"""拆出首尾纯空白 span,避免把段首 emphasis-only 空格包进 HTML 外层后无法 trim。"""
start = 0
end = len(text_spans)
- while start < end and not str(text_spans[start].get('content', '')).strip():
+ while start < end and not str(text_spans[start].get("content", "")).strip():
start += 1
- while end > start and not str(text_spans[end - 1].get('content', '')).strip():
+ while end > start and not str(text_spans[end - 1].get("content", "")).strip():
end -= 1
return text_spans[:start], text_spans[start:end], text_spans[end:]
@@ -461,16 +452,16 @@ def _get_markdown_style_key(
if not style_set:
return None
if style_set & OFFICE_COMPLEX_HTML_STYLES:
- return ''
+ return ""
style_key = frozenset(style_set)
if style_key in OFFICE_MARKDOWN_STYLE_WRAPPERS:
return style_key
- return ''
+ return ""
def _is_simple_markdown_style(style: list | tuple | set | None) -> bool:
"""判断样式是否适合保留为简单 Markdown 输出。"""
- return _get_markdown_style_key(style) != ''
+ return _get_markdown_style_key(style) != ""
def _has_markdown_wrapper(
@@ -483,95 +474,95 @@ def _has_markdown_wrapper(
return _get_markdown_style_key(style) in OFFICE_MARKDOWN_STYLE_WRAPPERS
-def _iter_para_inline_spans(para_block):
+def _iter_para_inline_spans(para_block: Block) -> Generator[Span, None, None]:
"""按 block 原始顺序遍历行内 span,供 auto 语法判定复用。"""
- for line in para_block.get('lines', []):
- for span in line.get('spans', []):
+ for line in para_block.lines:
+ for span in line.spans:
yield span
-def _hyperlink_requires_html(span: dict) -> bool:
+def _hyperlink_requires_html(span: Span) -> bool:
"""判断 hyperlink 是否存在混合或复杂样式,需要整块切到 HTML。"""
- children = span.get('children') or []
+ children = span.get("children") or []
if not children:
- return not _is_simple_markdown_style(span.get('style', []))
+ return not _is_simple_markdown_style(span.get("style", []))
child_style_keys = set()
for child in children:
- if child.get('type') != ContentType.TEXT:
+ if child.get("type") != ContentType.TEXT:
return True
- content = str(child.get('content', ''))
+ content = str(child.get("content", ""))
if not content.strip():
continue
- child_style = child.get('style', [])
+ child_style = child.get("style", [])
child_style_key = _get_markdown_style_key(child_style)
- if child_style_key == '':
+ if child_style_key == "":
return True
child_style_keys.add(child_style_key)
return len(child_style_keys) > 1
-def _iter_block_inline_units(para_block):
+def _iter_block_inline_units(para_block: Block) -> Generator[dict[str, Any], None, None]:
"""把 block 展开为线性文本单元,用于判断 Markdown 边界风险。"""
- if para_block.get('type') == BlockType.TITLE:
- section_number = para_block.get('section_number', '')
- if para_block.get('is_numbered_style', False) and section_number:
+ if para_block.type == BlockType.TITLE:
+ section_number = para_block.get("section_number", "")
+ if para_block.get("is_numbered_style", False) and section_number:
yield {
- 'span_type': ContentType.TEXT,
- 'content': f'{section_number} ',
- 'style': [],
+ "span_type": ContentType.TEXT,
+ "content": f"{section_number} ",
+ "style": [],
}
for span in _iter_para_inline_spans(para_block):
- span_type = span.get('type')
+ span_type = span.type
if span_type == ContentType.TEXT:
yield {
- 'span_type': ContentType.TEXT,
- 'content': str(span.get('content', '')),
- 'style': span.get('style', []),
+ "span_type": ContentType.TEXT,
+ "content": span.content,
+ "style": span.get("style", []),
}
elif span_type == ContentType.HYPERLINK:
- children = span.get('children') or []
+ children = span.get("children") or []
if children:
for child in children:
- if child.get('type') != ContentType.TEXT:
+ if child.get("type") != ContentType.TEXT:
continue
yield {
- 'span_type': ContentType.HYPERLINK,
- 'content': str(child.get('content', '')),
- 'style': child.get('style', []),
+ "span_type": ContentType.HYPERLINK,
+ "content": str(child.get("content", "")),
+ "style": child.get("style", []),
}
else:
yield {
- 'span_type': ContentType.HYPERLINK,
- 'content': str(span.get('content', '')),
- 'style': span.get('style', []),
+ "span_type": ContentType.HYPERLINK,
+ "content": span.content,
+ "style": span.get("style", []),
}
elif span_type in {ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}:
yield {
- 'span_type': span_type,
- 'content': str(span.get('content', '')),
- 'style': [],
+ "span_type": span_type,
+ "content": span.content,
+ "style": [],
}
-def _select_block_inline_syntax(para_block) -> str:
+def _select_block_inline_syntax(para_block: Block) -> str:
"""按 block 粒度选择 inline 输出语法:简单样式用 Markdown,复杂样式统一 HTML。"""
units = list(_iter_block_inline_units(para_block))
markdown_style_keys = set()
for span in _iter_para_inline_spans(para_block):
- span_type = span.get('type')
+ span_type = span.type
if span_type == ContentType.HYPERLINK and _hyperlink_requires_html(span):
return OFFICE_INLINE_SYNTAX_HTML
for unit in units:
- content = unit.get('content', '')
+ content = unit.get("content", "")
if not content:
continue
- style_key = _get_markdown_style_key(unit.get('style'))
- if style_key == '':
+ style_key = _get_markdown_style_key(unit.get("style"))
+ if style_key == "":
return OFFICE_INLINE_SYNTAX_HTML
if style_key is not None:
markdown_style_keys.add(style_key)
@@ -584,8 +575,8 @@ def _select_block_inline_syntax(para_block) -> str:
def _append_style_range_token(
tokens: list[StyleRangeToken],
rendered_content: str,
- style: list | set | None,
-):
+ style: list[str] | set[str] | None,
+) -> None:
"""追加一个可参与 HTML 范围合并的文本 token,空内容不进入 wrapper diff。"""
if not rendered_content:
return
@@ -600,9 +591,9 @@ def _append_style_range_token(
def _extend_style_range_tokens(
tokens: list[StyleRangeToken],
original_content: str,
- span_style: list,
+ span_style: list[str],
inline_syntax: str,
-):
+) -> None:
"""把原始 text span 拆成 HTML 合并 token,并保留现有可见空格 marker 规则。"""
if not original_content:
return
@@ -610,7 +601,7 @@ def _extend_style_range_tokens(
marker = _get_visible_space_marker(span_style)
if marker:
render_style = list(span_style or [])
- if marker == '-' and not _is_ascii_space_only(original_content):
+ if marker == "-" and not _is_ascii_space_only(original_content):
rendered_content = _render_text_with_edge_space_markers(
original_content,
marker,
@@ -622,11 +613,8 @@ def _extend_style_range_tokens(
marker,
inline_syntax,
)
- ignored_style = 'underline' if marker == '_' else 'strikethrough'
- render_style = [
- name for name in render_style
- if name != ignored_style
- ]
+ ignored_style = "underline" if marker == "_" else "strikethrough"
+ render_style = [name for name in render_style if name != ignored_style]
else:
rendered_content = _render_text_with_edge_space_markers(
original_content,
@@ -643,8 +631,8 @@ def _extend_style_range_tokens(
escaped_content = _escape_office_inline_text(original_content, inline_syntax)
content_stripped = escaped_content.strip()
if content_stripped:
- leading = escaped_content[:len(escaped_content) - len(escaped_content.lstrip())]
- trailing = escaped_content[len(escaped_content.rstrip()):]
+ leading = escaped_content[: len(escaped_content) - len(escaped_content.lstrip())]
+ trailing = escaped_content[len(escaped_content.rstrip()) :]
if leading:
_append_style_range_token(
tokens,
@@ -675,8 +663,8 @@ def _build_style_range_tokens(
for span in text_spans:
_extend_style_range_tokens(
tokens,
- str(span.get('content', '')),
- span.get('style', []),
+ str(span.get("content", "")),
+ span.get("style", []),
inline_syntax,
)
return tokens
@@ -686,31 +674,31 @@ def _style_range_stack(token: StyleRangeToken) -> list[str]:
"""按外到内顺序生成 HTML block 需要打开的 wrapper 栈。"""
style = token.style
stack = []
- if 'emphasis' in style:
- stack.append('emphasis')
- if 'strikethrough' in style:
- stack.append('strikethrough')
- if 'italic' in style:
- stack.append('italic')
- if 'bold' in style:
- stack.append('bold')
- if 'underline' in style:
- stack.append('underline')
- if 'superscript' in style:
- stack.append('superscript')
- elif 'subscript' in style:
- stack.append('subscript')
+ if "emphasis" in style:
+ stack.append("emphasis")
+ if "strikethrough" in style:
+ stack.append("strikethrough")
+ if "italic" in style:
+ stack.append("italic")
+ if "bold" in style:
+ stack.append("bold")
+ if "underline" in style:
+ stack.append("underline")
+ if "superscript" in style:
+ stack.append("superscript")
+ elif "subscript" in style:
+ stack.append("subscript")
return stack
def _style_wrapper_open(wrapper: str) -> str:
"""返回指定 wrapper 的打开标记。"""
- return STYLE_WRAPPER_OPEN.get(wrapper, '')
+ return STYLE_WRAPPER_OPEN.get(wrapper, "")
def _style_wrapper_close(wrapper: str) -> str:
"""返回指定 wrapper 的关闭标记。"""
- return STYLE_WRAPPER_CLOSE.get(wrapper, '')
+ return STYLE_WRAPPER_CLOSE.get(wrapper, "")
def _common_stack_prefix_len(
@@ -746,25 +734,25 @@ def _render_style_range_tokens(tokens: list[StyleRangeToken]) -> str:
for wrapper in reversed(current_stack):
rendered_parts.append(_style_wrapper_close(wrapper))
- return ''.join(rendered_parts)
+ return "".join(rendered_parts)
def _append_markdown_grouped_text_parts(
parts: list[RenderedPart],
- text_spans: list[dict],
-):
+ text_spans: list[dict[str, Any]],
+) -> None:
"""渲染简单 Markdown block,按可枚举 style key 合并相邻等价片段。"""
pending_content = []
pending_style = None
pending_style_key = None
has_pending = False
- def flush_pending():
+ def flush_pending() -> None:
nonlocal pending_content, pending_style, pending_style_key, has_pending
if pending_content:
_append_text_part(
parts,
- ''.join(pending_content),
+ "".join(pending_content),
list(pending_style or []),
OFFICE_INLINE_SYNTAX_MARKDOWN,
)
@@ -774,7 +762,7 @@ def _append_markdown_grouped_text_parts(
has_pending = False
for span in text_spans:
- span_style = tuple(span.get('style', []))
+ span_style = tuple(span.get("style", []))
span_style_key = _get_markdown_style_key(span_style)
if not has_pending:
pending_style = span_style
@@ -785,15 +773,15 @@ def _append_markdown_grouped_text_parts(
pending_style = span_style
pending_style_key = span_style_key
has_pending = True
- pending_content.append(str(span.get('content', '')))
+ pending_content.append(str(span.get("content", "")))
flush_pending()
def _append_style_grouped_text_parts(
parts: list[RenderedPart],
- text_spans: list[dict],
+ text_spans: list[dict[str, Any]],
inline_syntax: str,
-):
+) -> None:
"""按 block 语法渲染连续文本 span:简单 Markdown,复杂 HTML。"""
if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
_append_markdown_grouped_text_parts(parts, text_spans)
@@ -803,8 +791,8 @@ def _append_style_grouped_text_parts(
for span in leading_spans:
_append_text_part(
parts,
- span.get('content', ''),
- span.get('style', []),
+ span.get("content", ""),
+ span.get("style", []),
inline_syntax,
)
@@ -821,8 +809,8 @@ def _append_style_grouped_text_parts(
for span in trailing_spans:
_append_text_part(
parts,
- span.get('content', ''),
- span.get('style', []),
+ span.get("content", ""),
+ span.get("style", []),
inline_syntax,
)
@@ -832,12 +820,14 @@ def _render_hyperlink_children_label(children: list[dict], inline_syntax: str) -
child_parts = []
child_text_spans = []
for child in children or []:
- if child.get('type') != ContentType.TEXT:
+ if child.get("type") != ContentType.TEXT:
continue
- child_text_spans.append({
- 'content': child.get('content', ''),
- 'style': child.get('style', []),
- })
+ child_text_spans.append(
+ {
+ "content": child.get("content", ""),
+ "style": child.get("style", []),
+ }
+ )
_append_style_grouped_text_parts(child_parts, child_text_spans, inline_syntax)
return _join_rendered_parts(child_parts).strip()
@@ -845,22 +835,18 @@ def _render_hyperlink_children_label(children: list[dict], inline_syntax: str) -
def _append_hyperlink_part(
parts: list[RenderedPart],
original_content: str,
- span_style: list,
+ span_style: list[str],
inline_syntax: str,
- url: str = '',
+ url: str = "",
plain_text_only: bool = False,
- children: list[dict] | None = None,
-):
+ children: list[dict[str, Any]] | None = None,
+) -> None:
"""渲染 hyperlink 片段;HTML block 使用 <a>,Markdown block 使用 []()。"""
if children:
styled_text = _render_hyperlink_children_label(children, inline_syntax)
if not styled_text:
return
- rendered_content = (
- styled_text
- if plain_text_only
- else _render_link(styled_text, url, inline_syntax)
- )
+ rendered_content = styled_text if plain_text_only else _render_link(styled_text, url, inline_syntax)
else:
stripped_content = original_content.strip()
if not stripped_content:
@@ -872,8 +858,8 @@ def _append_hyperlink_part(
inline_syntax,
)
if plain_text_only:
- leading = original_content[:len(original_content) - len(original_content.lstrip())]
- trailing = original_content[len(original_content.rstrip()):]
+ leading = original_content[: len(original_content) - len(original_content.lstrip())]
+ trailing = original_content[len(original_content.rstrip()) :]
rendered_content = leading + styled_text + trailing
else:
rendered_content = _render_link(styled_text, url, inline_syntax)
@@ -886,22 +872,22 @@ def _append_hyperlink_part(
)
-def merge_para_with_text(para_block, escape_text_block_prefix=True):
+def merge_para_with_text(para_block: Block, escape_text_block_prefix: bool = True) -> str:
"""将 Office 段落 block 渲染为 Markdown/HTML 混合文本,按 block 自动选择行内语法。"""
inline_syntax = _select_block_inline_syntax(para_block)
parts = []
text_span_buffer = []
- def flush_text_span_buffer():
+ def flush_text_span_buffer() -> None:
"""遇到公式、超链接等边界时落盘连续文本 span,避免跨语义边界合并。"""
if not text_span_buffer:
return
_append_style_grouped_text_parts(parts, text_span_buffer, inline_syntax)
text_span_buffer.clear()
- if para_block['type'] == BlockType.TITLE:
- if para_block.get('is_numbered_style', False):
- section_number = para_block.get('section_number', '')
+ if para_block.type == BlockType.TITLE:
+ if para_block.get("is_numbered_style", False):
+ section_number = para_block.get("section_number", "")
if section_number:
parts.append(
_make_rendered_part(
@@ -910,19 +896,21 @@ def merge_para_with_text(para_block, escape_text_block_prefix=True):
)
)
- for line in para_block['lines']:
- for span in line['spans']:
- span_type = span['type']
- span_style = span.get('style', [])
+ for line in para_block.lines:
+ for span in line.spans:
+ span_type = span.type
+ span_style = span.get("style", [])
if span_type == ContentType.TEXT:
- text_span_buffer.append({
- 'content': span.get('content', ''),
- 'style': span_style,
- })
+ text_span_buffer.append(
+ {
+ "content": span.content,
+ "style": span_style,
+ }
+ )
elif span_type == ContentType.INLINE_EQUATION:
flush_text_span_buffer()
- content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
+ content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"
content = content.strip()
if content:
parts.append(
@@ -933,7 +921,7 @@ def merge_para_with_text(para_block, escape_text_block_prefix=True):
)
elif span_type == ContentType.INTERLINE_EQUATION:
flush_text_span_buffer()
- 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"
content = content.strip()
if content:
parts.append(
@@ -946,18 +934,18 @@ def merge_para_with_text(para_block, escape_text_block_prefix=True):
flush_text_span_buffer()
_append_hyperlink_part(
parts,
- span['content'],
+ span.content,
span_style,
inline_syntax,
- url=span.get('url', ''),
- children=span.get('children'),
+ url=span.get("url", ""),
+ children=span.get("children"),
)
else:
flush_text_span_buffer()
flush_text_span_buffer()
para_text = _join_rendered_parts(parts)
- if para_block.get('type') == BlockType.TEXT:
+ if para_block.type == BlockType.TEXT:
para_text = _strip_text_block_markdown_edges(para_text)
para_text = _escape_standalone_marker_rule(para_text)
if escape_text_block_prefix:
diff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/backend/office/mkcontent/output_builders.py
index bdb8aa7e..a711f720 100644
--- a/mineru/backend/office/mkcontent/output_builders.py
+++ b/mineru/backend/office/mkcontent/output_builders.py
@@ -1,8 +1,13 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import re
+from collections.abc import Generator
+from typing import Any
-from mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2
-from mineru.backend.office.mkcontent.inline_renderer import (
+from ....types import Block, Line, Span
+from ....utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode
+from .inline_renderer import (
_append_hyperlink_part,
_append_text_part,
_apply_configured_style,
@@ -34,8 +39,8 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
if not html:
return html
return re.sub(
- r'<eq>(.*?)</eq>',
- lambda m: f' {inline_left_delimiter}{m.group(1)}{inline_right_delimiter} ',
+ r"<eq>(.*?)</eq>",
+ lambda m: f" {inline_left_delimiter}{m.group(1)}{inline_right_delimiter} ",
html,
flags=re.DOTALL,
)
@@ -49,50 +54,50 @@ def _format_embedded_html(html: str, img_buket_path: str) -> str:
def _build_media_path(img_buket_path: str, image_path: str) -> str:
"""构造图片展示路径,空图片路径保持为空。"""
if not image_path:
- return ''
+ return ""
if not img_buket_path:
return image_path
return f"{img_buket_path}/{image_path}"
-def _get_ordered_list_start(list_block):
+def _get_ordered_list_start(list_block: Block) -> int:
"""读取有序列表起始编号,兼容旧版数据缺少 start 字段的情况。"""
try:
- return int(list_block.get('start', 1))
+ return int(list_block.get("start", 1))
except (TypeError, ValueError):
return 1
-def _get_list_ilevel(list_block) -> int:
+def _get_list_ilevel(list_block: Block) -> int:
"""安全读取 DOCX 列表原始 ilevel,异常值按顶层 0 处理。"""
try:
- return int(list_block.get('ilevel', 0))
+ return int(list_block.get("ilevel", 0))
except (TypeError, ValueError):
return 0
-def _get_relative_list_ilevel(list_block, root_ilevel: int) -> int:
+def _get_relative_list_ilevel(list_block: Block, root_ilevel: int) -> int:
"""将 DOCX 原始 ilevel 转为当前列表树内的相对缩进层级。"""
return max(_get_list_ilevel(list_block) - root_ilevel, 0)
-def _flatten_list_items(list_block, root_ilevel: int | None = None):
+def _flatten_list_items(list_block: Block, root_ilevel: int | None = None) -> list[str]:
"""Recursively flatten nested list blocks into a list of prefixed item strings."""
items = []
if root_ilevel is None:
root_ilevel = _get_list_ilevel(list_block)
relative_ilevel = _get_relative_list_ilevel(list_block, root_ilevel)
- attribute = list_block.get('attribute', 'unordered')
- indent = ' ' * relative_ilevel
+ attribute = list_block.get("attribute", "unordered")
+ indent = " " * relative_ilevel
ordered_counter = _get_ordered_list_start(list_block)
- for block in list_block.get('blocks', []):
- if block['type'] in [BlockType.LIST, BlockType.INDEX]:
+ for block in list_block.blocks:
+ if block["type"] in [BlockType.LIST, BlockType.INDEX]:
items.extend(_flatten_list_items(block, root_ilevel))
else:
item_text = merge_para_with_text(block, escape_text_block_prefix=False)
if item_text.strip():
- if attribute == 'ordered':
+ if attribute == "ordered":
items.append(f"{indent}{ordered_counter}. {item_text}")
ordered_counter += 1
else:
@@ -101,31 +106,31 @@ def _flatten_list_items(list_block, root_ilevel: int | None = None):
return items
-def _flatten_list_items_v2(list_block, root_ilevel: int | None = None):
+def _flatten_list_items_v2(list_block: Block, root_ilevel: int | None = None) -> list[dict[str, Any]]:
"""Recursively flatten nested list blocks into v2-structured item dicts."""
items = []
if root_ilevel is None:
root_ilevel = _get_list_ilevel(list_block)
relative_ilevel = _get_relative_list_ilevel(list_block, root_ilevel)
- attribute = list_block.get('attribute', 'unordered')
+ attribute = list_block.get("attribute", "unordered")
ordered_counter = _get_ordered_list_start(list_block)
- for block in list_block.get('blocks', []):
- if block['type'] in [BlockType.LIST, BlockType.INDEX]:
+ for block in list_block.blocks:
+ if block["type"] in [BlockType.LIST, BlockType.INDEX]:
items.extend(_flatten_list_items_v2(block, root_ilevel))
else:
item_content = merge_para_with_text_v2(block)
if item_content:
- if attribute == 'ordered':
+ if attribute == "ordered":
prefix = f"{' ' * relative_ilevel}{ordered_counter}."
ordered_counter += 1
else:
prefix = f"{' ' * relative_ilevel}-"
item = {
- 'item_type': 'text',
- 'ilevel': relative_ilevel,
- 'prefix': prefix,
- 'item_content': item_content,
+ "item_type": "text",
+ "ilevel": relative_ilevel,
+ "prefix": prefix,
+ "item_content": item_content,
}
anchor = block.get("anchor")
if isinstance(anchor, str) and anchor.strip():
@@ -135,27 +140,29 @@ def _flatten_list_items_v2(list_block, root_ilevel: int | None = None):
return items
-def merge_list_to_markdown(list_block):
+def merge_list_to_markdown(list_block: Block) -> str:
"""Recursively convert a nested list block to markdown text."""
- return '\n'.join(_flatten_list_items(list_block)) + '\n'
+ return "\n".join(_flatten_list_items(list_block)) + "\n"
-def _collect_index_span_items(text_block):
+def _collect_index_span_items(text_block: Block) -> list[tuple[str, str, list[str]]]:
"""按原始顺序收集目录叶子节点中的 span 三元组。"""
span_items = []
- for line in text_block.get('lines', []):
- for span in line.get('spans', []):
- span_items.append((
- span.get('content', ''),
- span.get('type'),
- span.get('style', []),
- ))
+ for line in text_block.lines:
+ for span in line.spans:
+ span_items.append(
+ (
+ span.get("content", ""),
+ span.get("type"),
+ span.get("style", []),
+ )
+ )
return span_items
-def _normalize_anchor(block) -> str | None:
+def _normalize_anchor(block: Block) -> str | None:
"""规范化 block 锚点,空值返回 None。"""
- anchor = block.get('anchor')
+ anchor = block.get("anchor")
if not isinstance(anchor, str) or not anchor.strip():
return None
return anchor.strip()
@@ -168,41 +175,41 @@ def _looks_like_index_page_token(token: str) -> bool:
return False
if len(token) > 12:
return False
- if re.search(r'[\u4e00-\u9fff]', token):
+ if re.search(r"[\u4e00-\u9fff]", token):
return False
- if re.fullmatch(r'\d+', token):
+ if re.fullmatch(r"\d+", token):
return True
- if re.fullmatch(r'[ivxlcdm]+', token.lower()):
+ if re.fullmatch(r"[ivxlcdm]+", token.lower()):
return True
- if re.fullmatch(r'[a-zA-Z]', token):
+ if re.fullmatch(r"[a-zA-Z]", token):
return True
return False
-def _strip_index_page_tail(span_items):
+def _strip_index_page_tail(span_items: list[tuple[str, str, list[str]]]) -> list[tuple[str, str, list[str]]]:
"""去掉目录叶子末尾 tab+页码,并把剩余 tab 转成普通空格。"""
last_tab_span_idx = -1
for i, (content, span_type, _) in enumerate(span_items):
- if span_type != ContentType.INLINE_EQUATION and '\t' in content:
+ if span_type != ContentType.INLINE_EQUATION and "\t" in content:
last_tab_span_idx = i
should_strip_page_tail = False
if last_tab_span_idx != -1:
last_tab_content = span_items[last_tab_span_idx][0]
- tab_tail = last_tab_content.rsplit('\t', 1)[1]
+ tab_tail = last_tab_content.rsplit("\t", 1)[1]
should_strip_page_tail = _looks_like_index_page_token(tab_tail)
stripped_span_items = []
for i, (content, span_type, span_style) in enumerate(span_items):
if span_type != ContentType.INLINE_EQUATION:
if i == last_tab_span_idx and should_strip_page_tail:
- content = content.rsplit('\t', 1)[0]
- content = content.replace('\t', ' ')
+ content = content.rsplit("\t", 1)[0]
+ content = content.replace("\t", " ")
stripped_span_items.append((content, span_type, span_style))
return stripped_span_items
-def _get_uniform_index_style(span_items) -> list | None:
+def _get_uniform_index_style(span_items: list[tuple[str, str, list[str]]]) -> list[str] | None:
"""如果目录叶子所有非公式 span 样式完全一致,则返回统一样式。"""
non_eq_styles = [
tuple(span_style)
@@ -217,25 +224,25 @@ def _get_uniform_index_style(span_items) -> list | None:
return None
-def _render_uniform_index_item(span_items, uniform_style, inline_syntax) -> str:
+def _render_uniform_index_item(
+ span_items: list[tuple[str, str, list[str]]], uniform_style: list[str], inline_syntax: str
+) -> str:
"""用统一样式渲染目录叶子,避免同样式片段产生碎片化 marker。"""
raw_parts = []
for content, span_type, _span_style in span_items:
if not content:
continue
if span_type == ContentType.INLINE_EQUATION:
- raw_parts.append(
- f'{inline_left_delimiter}{content}{inline_right_delimiter}'
- )
+ raw_parts.append(f"{inline_left_delimiter}{content}{inline_right_delimiter}")
else:
raw_parts.append(_escape_office_inline_text(content, inline_syntax))
- item_text = ''.join(raw_parts).strip()
+ item_text = "".join(raw_parts).strip()
if not item_text:
- return ''
+ return ""
return _apply_configured_style(item_text, uniform_style, inline_syntax)
-def _render_mixed_index_item(span_items, inline_syntax) -> str:
+def _render_mixed_index_item(span_items: list[tuple[str, str, list[str]]], inline_syntax: str) -> str:
"""逐 span 渲染目录叶子,超链接 span 在目录中仅保留可见文本。"""
rendered_parts = []
for content, span_type, span_style in span_items:
@@ -245,7 +252,7 @@ def _render_mixed_index_item(span_items, inline_syntax) -> str:
rendered_parts.append(
_make_rendered_part(
span_type,
- f'{inline_left_delimiter}{content}{inline_right_delimiter}',
+ f"{inline_left_delimiter}{content}{inline_right_delimiter}",
)
)
elif span_type == ContentType.HYPERLINK:
@@ -266,7 +273,7 @@ def _render_mixed_index_item(span_items, inline_syntax) -> str:
return _join_rendered_parts(rendered_parts).strip()
-def _render_index_leaf_item(text_block, indent: str) -> str | None:
+def _render_index_leaf_item(text_block: Block, indent: str) -> str | None:
"""渲染单个目录叶子节点,并在有锚点时挂载内部链接。"""
inline_syntax = _select_block_inline_syntax(text_block)
span_items = _collect_index_span_items(text_block)
@@ -292,56 +299,53 @@ def _render_index_leaf_item(text_block, indent: str) -> str | None:
return f"{indent}- {item_text}"
-def _flatten_index_items(index_block):
+def _flatten_index_items(index_block: Block) -> list[str]:
"""递归展平目录 block,保留目录锚点和目录项样式。"""
items = []
- indent = ' ' * index_block.get('ilevel', 0)
- for child in index_block.get('blocks', []):
- if child.get('type') == BlockType.INDEX:
+ indent = " " * index_block.get("ilevel", 0)
+ for child in index_block.blocks:
+ if child.get("type") == BlockType.INDEX:
items.extend(_flatten_index_items(child))
- elif child.get('type') == BlockType.TEXT:
+ elif child.get("type") == BlockType.TEXT:
item_text = _render_index_leaf_item(child, indent)
if item_text:
items.append(item_text)
return items
-def merge_index_to_markdown(index_block):
+def merge_index_to_markdown(index_block: Block) -> str:
"""Convert a nested index (TOC) block to markdown with hyperlinks."""
- return '\n'.join(_flatten_index_items(index_block)) + '\n'
+ return "\n".join(_flatten_index_items(index_block)) + "\n"
-def _iter_child_blocks(para_block, block_type: str):
+def _iter_child_blocks(para_block: Block, block_type: str) -> Generator[Block, None, None]:
"""按原始顺序遍历指定类型的子 block。"""
- for block in para_block.get('blocks', []):
- if block.get('type') == block_type:
+ for block in para_block.blocks:
+ if block.get("type") == block_type:
yield block
-def _iter_block_spans(block):
+def _iter_block_spans(block: Block) -> Generator[Span, None, None]:
"""按原始顺序遍历 block 下所有 span。"""
- for line in block.get('lines', []):
- for span in line.get('spans', []):
+ for line in block.lines:
+ for span in line.spans:
yield span
-def _iter_body_spans(para_block, body_type: str, span_type: str):
+def _iter_body_spans(para_block: Block, body_type: str, span_type: str) -> Generator[Span, None, None]:
"""遍历视觉类 block 的 body span,统一 image/table/chart 的查找方式。"""
for block in _iter_child_blocks(para_block, body_type):
for span in _iter_block_spans(block):
- if span.get('type') == span_type:
+ if span.get("type") == span_type:
yield span
-def _collect_caption_texts(para_block, caption_type: str) -> list[str]:
+def _collect_caption_texts(para_block: Block, caption_type: str) -> list[str]:
"""收集 legacy markdown/content_list 使用的 caption 文本。"""
- return [
- merge_para_with_text(block)
- for block in _iter_child_blocks(para_block, caption_type)
- ]
+ return [merge_para_with_text(block) for block in _iter_child_blocks(para_block, caption_type)]
-def _collect_caption_v2(para_block, caption_type: str) -> list[dict]:
+def _collect_caption_v2(para_block: Block, caption_type: str) -> list[dict[str, Any]]:
"""收集 content_list_v2 使用的结构化 caption spans。"""
caption_content = []
for block in _iter_child_blocks(para_block, caption_type):
@@ -349,20 +353,18 @@ def _collect_caption_v2(para_block, caption_type: str) -> list[dict]:
return caption_content
-def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=None):
+def mk_blocks_to_markdown(
+ para_blocks: list[Block], make_mode: MakeMode, img_buket_path: str = "", page_idx: int | None = None
+) -> str:
page_markdown = []
for para_block in para_blocks:
- para_text = ''
- para_type = para_block['type']
+ para_text = ""
+ para_type = para_block["type"]
if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:
para_text = merge_para_with_text(para_block)
if para_type == BlockType.TEXT:
bookmark_anchor = para_block.get("anchor")
- if (
- isinstance(bookmark_anchor, str)
- and bookmark_anchor.strip()
- and bookmark_anchor.strip().startswith("_Toc")
- ):
+ if isinstance(bookmark_anchor, str) and bookmark_anchor.strip() and bookmark_anchor.strip().startswith("_Toc"):
para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{para_text}'
elif para_type == BlockType.LIST:
para_text = merge_list_to_markdown(para_block)
@@ -375,7 +377,7 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():
para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'
else:
- para_text = f'{"#" * title_level} {title_text}'
+ para_text = f"{'#' * title_level} {title_text}"
elif para_type == BlockType.IMAGE:
if make_mode == MakeMode.NLP_MD:
continue
@@ -385,13 +387,13 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
BlockType.IMAGE_BODY,
ContentType.IMAGE,
):
- if span.get('image_path', ''):
+ if span.get("image_path", ""):
para_text += f"![]({img_buket_path}/{span['image_path']})"
for caption_text in _collect_caption_texts(
para_block,
BlockType.IMAGE_CAPTION,
):
- para_text += ' \n' + caption_text
+ para_text += " \n" + caption_text
elif para_type == BlockType.TABLE:
if make_mode == MakeMode.NLP_MD:
@@ -407,7 +409,7 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
para_block,
BlockType.TABLE_CAPTION,
):
- para_text += ' \n' + caption_text
+ para_text += " \n" + caption_text
elif para_type == BlockType.CHART:
if make_mode == MakeMode.NLP_MD:
continue
@@ -423,18 +425,18 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
para_block,
BlockType.CHART_CAPTION,
):
- para_text += ' \n' + caption_text
- if para_text.strip() == '':
+ para_text += " \n" + caption_text
+ if para_text.strip() == "":
continue
else:
# page_markdown.append(para_text.strip())
- page_markdown.append(para_text.strip('\r\n'))
+ page_markdown.append(para_text.strip("\r\n"))
return page_markdown
-def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
- para_type = para_block['type']
+def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx: int | None) -> list[dict[str, Any]]:
+ para_type = para_block["type"]
para_content = {}
if para_type in [
BlockType.TEXT,
@@ -443,65 +445,61 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
BlockType.PAGE_FOOTNOTE,
]:
para_content = {
- 'type': para_type,
- 'text': merge_para_with_text(para_block),
+ "type": para_type,
+ "text": merge_para_with_text(para_block),
}
elif para_type == BlockType.LIST:
para_content = {
- 'type': para_type,
- 'list_items': _flatten_list_items(para_block),
+ "type": para_type,
+ "list_items": _flatten_list_items(para_block),
}
elif para_type == BlockType.INDEX:
para_content = {
- 'type': para_type,
- 'list_items': _flatten_index_items(para_block),
+ "type": para_type,
+ "list_items": _flatten_index_items(para_block),
}
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
para_content = {
- 'type': ContentType.TEXT,
- 'text': merge_para_with_text(para_block),
+ "type": ContentType.TEXT,
+ "text": merge_para_with_text(para_block),
}
if title_level != 0:
- para_content['text_level'] = title_level
+ para_content["text_level"] = title_level
elif para_type == BlockType.INTERLINE_EQUATION:
para_content = {
- 'type': ContentType.EQUATION,
- 'text': merge_para_with_text(para_block),
- 'text_format': 'latex',
+ "type": ContentType.EQUATION,
+ "text": merge_para_with_text(para_block),
+ "text_format": "latex",
}
elif para_type == BlockType.IMAGE:
- para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: []}
+ para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: []}
for span in _iter_body_spans(
para_block,
BlockType.IMAGE_BODY,
ContentType.IMAGE,
):
- if span.get('image_path', ''):
- para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
- para_content[BlockType.IMAGE_CAPTION].extend(
- _collect_caption_texts(para_block, BlockType.IMAGE_CAPTION)
- )
+ if span.get("image_path", ""):
+ para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ para_content[BlockType.IMAGE_CAPTION].extend(_collect_caption_texts(para_block, BlockType.IMAGE_CAPTION))
elif para_type == BlockType.TABLE:
- para_content = {'type': ContentType.TABLE, BlockType.TABLE_CAPTION: []}
+ para_content = {"type": ContentType.TABLE, BlockType.TABLE_CAPTION: []}
for span in _iter_body_spans(
para_block,
BlockType.TABLE_BODY,
ContentType.TABLE,
):
- if span.get('html', ''):
+ if span.get("html", ""):
para_content[BlockType.TABLE_BODY] = _format_embedded_html(
- span['html'],
+ span["html"],
img_buket_path,
)
- para_content[BlockType.TABLE_CAPTION].extend(
- _collect_caption_texts(para_block, BlockType.TABLE_CAPTION)
- )
+ para_content[BlockType.TABLE_CAPTION].extend(_collect_caption_texts(para_block, BlockType.TABLE_CAPTION))
elif para_type == BlockType.CHART:
para_content = {
- 'type': ContentType.CHART,
- 'img_path': '',
- 'content': '',
+ "type": ContentType.CHART,
+ "img_path": "",
+ "content": "",
BlockType.CHART_CAPTION: [],
}
for span in _iter_body_spans(
@@ -509,20 +507,18 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
BlockType.CHART_BODY,
ContentType.CHART,
):
- para_content['img_path'] = _build_media_path(
+ para_content["img_path"] = _build_media_path(
img_buket_path,
- span.get('image_path', ''),
+ span.get("image_path", ""),
)
- if span.get('content', ''):
- para_content['content'] = _format_embedded_html(
- span['content'],
+ if span.get("content", ""):
+ para_content["content"] = _format_embedded_html(
+ span["content"],
img_buket_path,
)
- para_content[BlockType.CHART_CAPTION].extend(
- _collect_caption_texts(para_block, BlockType.CHART_CAPTION)
- )
+ para_content[BlockType.CHART_CAPTION].extend(_collect_caption_texts(para_block, BlockType.CHART_CAPTION))
- para_content['page_idx'] = page_idx
+ para_content["page_idx"] = page_idx
anchor = para_block.get("anchor")
if isinstance(anchor, str) and anchor.strip():
para_content["anchor"] = anchor.strip()
@@ -530,8 +526,8 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
return para_content
-def make_blocks_to_content_list_v2(para_block, img_buket_path):
- para_type = para_block['type']
+def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> list[dict[str, Any]]:
+ para_type = para_block["type"]
para_content = {}
if para_type in [
BlockType.HEADER,
@@ -547,60 +543,57 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
else:
raise ValueError(f"Unknown para_type: {para_type}")
para_content = {
- 'type': content_type,
- 'content': {
+ "type": content_type,
+ "content": {
f"{content_type}_content": merge_para_with_text_v2(para_block),
- }
+ },
}
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
if title_level != 0:
para_content = {
- 'type': ContentTypeV2.TITLE,
- 'content': {
- "title_content": merge_para_with_text_v2(para_block),
- "level": title_level
- }
+ "type": ContentTypeV2.TITLE,
+ "content": {"title_content": merge_para_with_text_v2(para_block), "level": title_level},
}
else:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
"paragraph_content": merge_para_with_text_v2(para_block),
- }
+ },
}
elif para_type in [
BlockType.TEXT,
]:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
- 'paragraph_content': merge_para_with_text_v2(para_block),
- }
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
+ "paragraph_content": merge_para_with_text_v2(para_block),
+ },
}
elif para_type == BlockType.INTERLINE_EQUATION:
_, math_content = get_body_data(para_block)
para_content = {
- 'type': ContentTypeV2.EQUATION_INTERLINE,
- 'content': {
- 'math_content': math_content,
- 'math_type': 'latex',
- }
+ "type": ContentTypeV2.EQUATION_INTERLINE,
+ "content": {
+ "math_content": math_content,
+ "math_type": "latex",
+ },
}
elif para_type == BlockType.IMAGE:
image_path, _ = get_body_data(para_block)
image_source = {
- 'path': f"{img_buket_path}/{image_path}",
+ "path": f"{img_buket_path}/{image_path}",
}
para_content = {
- 'type': ContentTypeV2.IMAGE,
- 'content': {
- 'image_source': image_source,
- 'image_caption': _collect_caption_v2(
+ "type": ContentTypeV2.IMAGE,
+ "content": {
+ "image_source": image_source,
+ "image_caption": _collect_caption_v2(
para_block,
BlockType.IMAGE_CAPTION,
),
- }
+ },
}
elif para_type == BlockType.TABLE:
_, html = get_body_data(para_block)
@@ -608,60 +601,56 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
table_nest_level = 2
else:
table_nest_level = 1
- if (
- "colspan" in html or
- "rowspan" in html or
- table_nest_level > 1
- ):
+ if "colspan" in html or "rowspan" in html or table_nest_level > 1:
table_type = ContentTypeV2.TABLE_COMPLEX
else:
table_type = ContentTypeV2.TABLE_SIMPLE
para_content = {
- 'type': ContentTypeV2.TABLE,
- 'content': {
- 'table_caption': _collect_caption_v2(
+ "type": ContentTypeV2.TABLE,
+ "content": {
+ "table_caption": _collect_caption_v2(
para_block,
BlockType.TABLE_CAPTION,
),
- 'html': _format_embedded_html(html, img_buket_path),
- 'table_type': table_type,
- 'table_nest_level': table_nest_level,
- }
+ "html": _format_embedded_html(html, img_buket_path),
+ "table_type": table_type,
+ "table_nest_level": table_nest_level,
+ },
}
elif para_type == BlockType.CHART:
image_path, chart_content = get_body_data(para_block)
para_content = {
- 'type': ContentTypeV2.CHART,
- 'content': {
- 'image_source': {
- 'path': _build_media_path(img_buket_path, image_path),
+ "type": ContentTypeV2.CHART,
+ "content": {
+ "image_source": {
+ "path": _build_media_path(img_buket_path, image_path),
},
- 'content': _format_embedded_html(chart_content, img_buket_path),
- 'chart_caption': _collect_caption_v2(
+ "content": _format_embedded_html(chart_content, img_buket_path),
+ "chart_caption": _collect_caption_v2(
para_block,
BlockType.CHART_CAPTION,
),
- }
+ },
}
elif para_type == BlockType.LIST:
list_type = ContentTypeV2.LIST_TEXT
- attribute = para_block.get('attribute', 'unordered')
+ attribute = para_block.get("attribute", "unordered")
para_content = {
- 'type': ContentTypeV2.LIST,
- 'content': {
- 'list_type': list_type,
- 'attribute': attribute,
- 'list_items': _flatten_list_items_v2(para_block),
- }
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": list_type,
+ "attribute": attribute,
+ "list_items": _flatten_list_items_v2(para_block),
+ },
}
elif para_type == BlockType.INDEX:
para_content = {
- 'type': ContentTypeV2.INDEX,
- 'content': {
- 'list_type': ContentTypeV2.LIST_TEXT,
- 'list_items': _flatten_list_items_v2(para_block),
- }
+ "type": ContentTypeV2.INDEX,
+ "content": {
+ "list_type": ContentTypeV2.LIST_TEXT,
+ "list_items": _flatten_list_items_v2(para_block),
+ },
}
anchor = para_block.get("anchor")
@@ -671,7 +660,7 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
return para_content
-def get_body_data(para_block):
+def get_body_data(para_block: Block) -> tuple[str, str]:
"""
Extract image_path and body content from para_block
Returns:
@@ -681,49 +670,49 @@ def get_body_data(para_block):
- Default: ('', '')
"""
- def get_data_from_spans(lines):
- synthetic_block = {'lines': lines}
+ def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
+ synthetic_block = {"lines": lines}
for span in _iter_block_spans(synthetic_block):
- span_type = span.get('type')
+ span_type = span.get("type")
if span_type == ContentType.TABLE:
- return span.get('image_path', ''), span.get('html', '')
+ return span.get("image_path", ""), span.get("html", "")
elif span_type == ContentType.CHART:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
elif span_type == ContentType.IMAGE:
- return span.get('image_path', ''), ''
+ return span.get("image_path", ""), ""
elif span_type == ContentType.INTERLINE_EQUATION:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
elif span_type == ContentType.TEXT:
- return '', span.get('content', '')
- return '', ''
+ return "", span.get("content", "")
+ return "", ""
# 处理嵌套的 blocks 结构
- if 'blocks' in para_block:
- for block in para_block['blocks']:
- block_type = block.get('type')
+ if "blocks" in para_block:
+ for block in para_block["blocks"]:
+ block_type = block.get("type")
if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:
- result = get_data_from_spans(block.get('lines', []))
- if result != ('', ''):
+ result = get_data_from_spans(block.lines)
+ if result != ("", ""):
return result
if block_type == BlockType.CHART_BODY:
return result
- return '', ''
+ return "", ""
# 处理直接包含 lines 的结构
- return get_data_from_spans(para_block.get('lines', []))
+ return get_data_from_spans(para_block.lines)
-def _span_has_content_for_v2(span: dict, visible_styles: set) -> bool:
+def _span_has_content_for_v2(span: Span, visible_styles: set[str]) -> bool:
"""判断 V2 span 是否应保留,支持 hyperlink children 的可见空白样式。"""
- content = span.get("content", '')
- span_style = span.get('style', [])
+ content = span.get("content", "")
+ span_style = span.get("style", [])
if content.strip():
return True
if content and span_style and any(s in visible_styles for s in span_style):
return True
- for child in span.get('children') or []:
- child_content = child.get('content', '')
- child_style = child.get('style', [])
+ for child in span.get("children") or []:
+ child_content = child.get("content", "")
+ child_style = child.get("style", [])
if child_content.strip():
return True
if child_content and child_style and any(s in visible_styles for s in child_style):
@@ -731,43 +720,45 @@ def _span_has_content_for_v2(span: dict, visible_styles: set) -> bool:
return False
-def merge_para_with_text_v2(para_block):
+def merge_para_with_text_v2(para_block: Block) -> str:
"""将 Office 段落转换为 content_list_v2 spans,避免原地修改 middle_json。"""
- _visible_styles = {'underline', 'strikethrough'}
+ _visible_styles = {"underline", "strikethrough"}
para_content = []
- if para_block.get('type') == BlockType.TITLE:
- section_number = para_block.get('section_number', '')
+ if para_block.get("type") == BlockType.TITLE:
+ section_number = para_block.get("section_number", "")
if section_number:
# v2 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。
- para_content.append({
- 'type': ContentTypeV2.SPAN_TEXT,
- 'content': f'{section_number} ',
- })
- for line in para_block['lines']:
- for span in line['spans']:
+ para_content.append(
+ {
+ "type": ContentTypeV2.SPAN_TEXT,
+ "content": f"{section_number} ",
+ }
+ )
+ for line in para_block["lines"]:
+ for span in line["spans"]:
if _span_has_content_for_v2(span, _visible_styles):
rendered_span = dict(span)
- if rendered_span['type'] == ContentType.INLINE_EQUATION:
- rendered_span['type'] = ContentTypeV2.SPAN_EQUATION_INLINE
+ if rendered_span["type"] == ContentType.INLINE_EQUATION:
+ rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINE
para_content.append(rendered_span)
return para_content
-def union_make(pdf_info_dict: list,
- make_mode: str,
- img_buket_path: str = '',
- ):
+def union_make(
+ pdf_info_dict: list[dict[str, Any]],
+ make_mode: MakeMode,
+ img_buket_path: str = "",
+) -> list[str]:
output_content = []
for page_info in pdf_info_dict:
- paras_of_layout = page_info.get('para_blocks')
- paras_of_discarded = page_info.get('discarded_blocks')
- page_idx = page_info.get('page_idx')
+ paras_of_layout = page_info.get("para_blocks")
+ paras_of_discarded = page_info.get("discarded_blocks")
+ page_idx = page_info.get("page_idx")
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
if not paras_of_layout:
continue
- page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path,
- page_idx=page_idx)
+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path, page_idx=page_idx)
output_content.extend(page_markdown)
elif make_mode == MakeMode.CONTENT_LIST:
para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])
@@ -787,7 +778,7 @@ def union_make(pdf_info_dict: list,
output_content.append(page_contents)
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
- return '\n\n'.join(output_content)
+ return "\n\n".join(output_content)
elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:
return output_content
return None
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index 0fcd899e..e8ffb811 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -1,16 +1,18 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import re
from collections import defaultdict
from typing import Any
-from ...types import PageInfo
+from ...types import Block, PageInfo
from ...utils.enum_class import BlockType
from ...version import __version__
from ..utils.html_image_utils import replace_inline_table_images, save_span_image_if_needed
from .office_magic_model import MagicModel
-def blocks_to_page_info(page_blocks: list, image_writer: Any, page_index: int) -> PageInfo:
+def blocks_to_page_info(page_blocks: list[dict[str, Any]], image_writer: Any, page_index: int) -> PageInfo:
"""将blocks转换为页面信息"""
magic_model = MagicModel(page_blocks)
@@ -21,23 +23,23 @@ def blocks_to_page_info(page_blocks: list, image_writer: Any, page_index: int) -
if image_writer:
# Write embedded images to local storage via image_writer
for img_block in image_blocks:
- for sub_block in img_block.get("blocks", []):
- if sub_block.get("type") != "image_body":
+ for sub_block in img_block.blocks:
+ if sub_block.type != "image_body":
continue
- for line in sub_block.get("lines", []):
- for span in line.get("spans", []):
+ for line in sub_block.lines:
+ for span in line.spans:
save_span_image_if_needed(span, image_writer, page_index)
replace_inline_table_images(table_blocks, image_writer, page_index)
# Replace inline base64 images inside chart content with local paths
for chart_block in chart_blocks:
- for sub_block in chart_block.get("blocks", []):
- if sub_block.get("type") != "chart_body":
+ for sub_block in chart_block.blocks:
+ if sub_block.type != "chart_body":
continue
- for line in sub_block.get("lines", []):
- for span in line.get("spans", []):
- if span.get("type") != "chart":
+ for line in sub_block.lines:
+ for span in line.spans:
+ if span.type != "chart":
continue
save_span_image_if_needed(span, image_writer, page_index)
@@ -72,7 +74,7 @@ def blocks_to_page_info(page_blocks: list, image_writer: Any, page_index: int) -
return page_info
-def _extract_section_parts_from_content(content: str, level: int):
+def _extract_section_parts_from_content(content: str, level: int) -> list[int] | None:
"""Try to extract a leading section number (e.g. '1.2.1') from title content.
Returns a list of ints [n1, n2, ..., nL] when the number of parts equals
@@ -89,16 +91,16 @@ def _extract_section_parts_from_content(content: str, level: int):
return None
-def _collect_index_text_blocks(index_block: dict, result: list[dict]) -> None:
+def _collect_index_text_blocks(index_block: Block, result: list[Block]) -> None:
"""Depth-first collect TOC leaf text blocks."""
- for child in index_block.get("blocks", []):
- if child.get("type") == BlockType.INDEX:
+ for child in index_block.blocks:
+ if child.type == BlockType.INDEX:
_collect_index_text_blocks(child, result)
- elif child.get("type") == BlockType.TEXT:
+ elif child.type == BlockType.TEXT:
result.append(child)
-def _link_index_entries_by_anchor(middle_json: dict) -> None:
+def _link_index_entries_by_anchor(middle_json: dict[str, Any]) -> None:
"""Keep TOC anchors only when they exist on parsed body blocks."""
pdf_info = middle_json.get("pdf_info", [])
valid_anchors: set[str] = set()
@@ -116,7 +118,7 @@ def _link_index_entries_by_anchor(middle_json: dict) -> None:
for block in page_info.get("para_blocks", []):
if block.get("type") != BlockType.INDEX:
continue
- toc_text_blocks: list[dict] = []
+ toc_text_blocks: list[Block] = []
_collect_index_text_blocks(block, toc_text_blocks)
for text_block in toc_text_blocks:
anchor = text_block.get("anchor")
@@ -130,7 +132,7 @@ def _link_index_entries_by_anchor(middle_json: dict) -> None:
text_block["anchor"] = anchor
-def result_to_middle_json(model_output_blocks_list, image_writer):
+def result_to_middle_json(model_output_blocks_list: list[list[dict[str, object]]], image_writer: object) -> dict[str, object]:
middle_json = {"pdf_info": [], "_backend": "office", "_version_name": __version__}
for index, page_blocks in enumerate(model_output_blocks_list):
page_info = blocks_to_page_info(page_blocks, image_writer, index)
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 02358579..690f0481 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -1,18 +1,18 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import html as html_lib
import re
-from typing import Literal
+from typing import Any, Literal
from urllib.parse import urlparse
-from loguru import logger
-
-from mineru.utils.enum_class import ContentType, BlockType
-from mineru.types import Block, Line, Span
-from mineru.utils.magic_model_utils import tie_up_category_by_index
+from ...types import Block, Line, Span
+from ...utils.enum_class import BlockType, ContentType
+from ...utils.magic_model_utils import tie_up_category_by_index
class MagicModel:
- def __init__(self, page_blocks: list) -> None:
+ def __init__(self, page_blocks: list[dict[str, Any]]) -> None:
self.page_blocks = page_blocks
blocks = []
@@ -23,7 +23,6 @@ class MagicModel:
# 解析每个块
for index, block_info in enumerate(page_blocks):
-
block_type = block_info["type"]
block_content = block_info.get("content", "")
if not block_content and block_type != BlockType.CHART:
@@ -125,7 +124,13 @@ class MagicModel:
self.ref_text_blocks.append(block)
elif block["type"] in [BlockType.PHONETIC]:
self.phonetic_blocks.append(block)
- elif block["type"] in [BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT, BlockType.PAGE_FOOTNOTE]:
+ elif block["type"] in [
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+ ]:
self.discarded_blocks.append(block)
elif block["type"] == BlockType.LIST:
self.list_blocks.append(block)
@@ -142,7 +147,6 @@ class MagicModel:
block["type"] = BlockType.TEXT
self.text_blocks.append(block)
-
def get_list_blocks(self) -> list[Block]:
return self.list_blocks
@@ -171,19 +175,19 @@ class MagicModel:
return self.discarded_blocks
-def _parse_style_list(style_str: str | None) -> list:
+def _parse_style_list(style_str: str | None) -> list[str]:
"""解析逗号分隔的 Office inline style 字符串。"""
if not style_str:
return []
- return [style.strip() for style in style_str.split(',') if style.strip()]
+ return [style.strip() for style in style_str.split(",") if style.strip()]
-def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re) -> tuple:
+def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re: re.Pattern[str]) -> tuple[str, list[Span], str]:
"""解析一个 hyperlink 内部的多个 text 子片段,并保留每段样式。"""
- url_start = hyperlink_content.find('<url>')
- url_end = hyperlink_content.find('</url>')
+ url_start = hyperlink_content.find("<url>")
+ url_end = hyperlink_content.find("</url>")
if url_start == -1 or url_end == -1 or url_end < url_start:
- return [], ''
+ return [], ""
children = []
pos = 0
@@ -192,13 +196,13 @@ def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re) -> tuple
if text_match is None or text_match.start() >= url_start:
break
- text_end = hyperlink_content.find('</text>', text_match.end())
+ text_end = hyperlink_content.find("</text>", text_match.end())
if text_end == -1 or text_end > url_start:
- return [], ''
+ return [], ""
child = {
"type": ContentType.TEXT,
- "content": hyperlink_content[text_match.end():text_end],
+ "content": hyperlink_content[text_match.end() : text_end],
}
style = _parse_style_list(text_match.group(1))
if style:
@@ -206,10 +210,10 @@ def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re) -> tuple
children.append(child)
pos = text_end + 7
- return children, hyperlink_content[url_start + 5:url_end]
+ return children, hyperlink_content[url_start + 5 : url_end]
-def parse_text_block_spans(content: str) -> list:
+def parse_text_block_spans(content: str) -> list[Span]:
"""
解析文本类block的content,提取其中的文本、行内公式、超链接和字体样式。
@@ -239,9 +243,9 @@ def parse_text_block_spans(content: str) -> list:
while pos < len(content):
# 查找行内公式标签 <eq>...</eq>
- eq_start = content.find('<eq>', pos)
+ eq_start = content.find("<eq>", pos)
# 查找超链接标签 <hyperlink>
- hyperlink_start = content.find('<hyperlink>', pos)
+ hyperlink_start = content.find("<hyperlink>", pos)
# 查找带样式的文本标签 <text ...>(顶层,不在 hyperlink 内部)
text_tag_match = _text_tag_re.search(content, pos)
text_tag_start = text_tag_match.start() if text_tag_match else -1
@@ -249,11 +253,11 @@ def parse_text_block_spans(content: str) -> list:
# 收集所有有效的标签位置
candidates = []
if eq_start != -1:
- candidates.append((eq_start, 'eq'))
+ candidates.append((eq_start, "eq"))
if hyperlink_start != -1:
- candidates.append((hyperlink_start, 'hyperlink'))
+ candidates.append((hyperlink_start, "hyperlink"))
if text_tag_start != -1:
- candidates.append((text_tag_start, 'text'))
+ candidates.append((text_tag_start, "text"))
# 没有找到任何标签,处理剩余文本
if not candidates:
@@ -272,10 +276,10 @@ def parse_text_block_spans(content: str) -> list:
spans.append(Span(type=ContentType.TEXT, content=text_before))
# 处理行内公式
- if next_tag_type == 'eq':
- eq_end = content.find('</eq>', next_tag_pos)
+ 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]
+ formula_content = content[next_tag_pos + 4 : eq_end]
spans.append(Span(type=ContentType.INLINE_EQUATION, content=formula_content))
pos = eq_end + 5
last_end = pos
@@ -285,17 +289,17 @@ def parse_text_block_spans(content: str) -> list:
break
# 处理带样式的文本标签
- elif next_tag_type == 'text':
- text_end = content.find('</text>', next_tag_pos)
+ elif next_tag_type == "text":
+ text_end = content.find("</text>", next_tag_pos)
if text_end != -1:
# text_tag_match 对应当前 next_tag_pos 的匹配
# 重新匹配确保位置对齐
- tag_open_end = content.find('>', next_tag_pos) + 1
+ 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)
if style_str:
- span["style"] = [s.strip() for s in style_str.split(',') if s.strip()]
+ span["style"] = [s.strip() for s in style_str.split(",") if s.strip()]
spans.append(span)
pos = text_end + 7
last_end = pos
@@ -305,11 +309,11 @@ def parse_text_block_spans(content: str) -> list:
break
# 处理超链接
- elif next_tag_type == 'hyperlink':
- hyperlink_end = content.find('</hyperlink>', next_tag_pos)
+ elif next_tag_type == "hyperlink":
+ hyperlink_end = content.find("</hyperlink>", next_tag_pos)
if hyperlink_end != -1:
# 提取超链接内容
- hyperlink_content = content[next_tag_pos + 11:hyperlink_end]
+ hyperlink_content = content[next_tag_pos + 11 : hyperlink_end]
# 解析内部的一个或多个 <text [style="..."]> 和一个 <url> 标签
children, link_url = _parse_hyperlink_text_children(
@@ -330,7 +334,7 @@ def parse_text_block_spans(content: str) -> list:
else:
span = Span(
type=ContentType.HYPERLINK,
- content=''.join(child["content"] for child in children),
+ content="".join(child["content"] for child in children),
)
span["url"] = link_url
span["children"] = children
@@ -349,7 +353,7 @@ def parse_text_block_spans(content: str) -> list:
return spans
-def parse_list_block(list_block: dict):
+def parse_list_block(list_block: dict[str, object]) -> Block:
"""
递归解析嵌套列表结构,生成与VLM一致的blocks结构。
@@ -391,7 +395,7 @@ def parse_list_block(list_block: dict):
return result
-def parse_index_block(index_block: dict):
+def parse_index_block(index_block: dict[str, object]) -> Block:
"""
递归解析嵌套索引结构(目录),生成与list一致的blocks结构。
@@ -473,23 +477,23 @@ def clean_table_html(html: str) -> str:
return ""
# 需要保留的属性(对表格结构有用)
- preserved_attrs = {'colspan', 'rowspan'}
+ preserved_attrs = {"colspan", "rowspan"}
# img 标签需要额外保留的属性(内联 base64 图片内容)
- img_preserved_attrs = {'src', 'alt', 'width', 'height'}
+ img_preserved_attrs = {"src", "alt", "width", "height"}
# a 标签只保留清洗后的 href,避免表格超链接在中间层被清掉。
- anchor_preserved_attrs = {'href'}
+ anchor_preserved_attrs = {"href"}
- def clean_tag(match):
+ def clean_tag(match: re.Match[str]) -> str:
"""清洗单个标签,只保留结构相关的属性"""
full_tag = match.group(0)
tag_name = match.group(1).lower()
# 自闭合标签的处理
- is_self_closing = full_tag.rstrip().endswith('/>')
+ is_self_closing = full_tag.rstrip().endswith("/>")
# img 标签额外保留图片相关属性(如内联 base64 src)
- current_preserved = preserved_attrs | (img_preserved_attrs if tag_name == 'img' else set())
- current_preserved |= anchor_preserved_attrs if tag_name == 'a' else set()
+ current_preserved = preserved_attrs | (img_preserved_attrs if tag_name == "img" else set())
+ current_preserved |= anchor_preserved_attrs if tag_name == "a" else set()
# 提取需要保留的属性
kept_attrs = []
@@ -518,33 +522,35 @@ def clean_table_html(html: str) -> str:
# 重建标签
if kept_attrs:
- attrs_str = ' ' + ' '.join(kept_attrs)
+ attrs_str = " " + " ".join(kept_attrs)
else:
- attrs_str = ''
+ attrs_str = ""
if is_self_closing:
- return f'<{tag_name}{attrs_str}/>'
+ return f"<{tag_name}{attrs_str}/>"
else:
- return f'<{tag_name}{attrs_str}>'
+ return f"<{tag_name}{attrs_str}>"
# 匹配开始标签(包括自闭合标签),捕获标签名
# 匹配 <tagname ...> 或 <tagname .../>
- tag_pattern = r'<(\w+)(?:\s+[^>]*)?\s*/?>'
+ tag_pattern = r"<(\w+)(?:\s+[^>]*)?\s*/?>"
result = re.sub(tag_pattern, clean_tag, html)
return result
-def isolated_formula_clean(txt):
+def isolated_formula_clean(txt: str) -> str:
latex = txt[:]
- if latex.startswith("\\["): latex = latex[2:]
- if latex.endswith("\\]"): latex = latex[:-2]
+ if latex.startswith("\\["):
+ latex = latex[2:]
+ if latex.endswith("\\]"):
+ latex = latex[:-2]
latex = latex.strip()
return latex
-def code_content_clean(content):
+def code_content_clean(content: str) -> str:
"""清理代码内容,移除Markdown代码块的开始和结束标记"""
if not content:
return ""
@@ -567,10 +573,11 @@ def code_content_clean(content):
return ""
-def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
+def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, object_block_type: str) -> list[dict[str, object]]:
"""基于index的主客体关联包装函数"""
+
# 定义获取主体和客体对象的函数
- def get_subjects():
+ def get_subjects() -> list[dict[str, object]]:
return list(
map(
lambda x: {"lines": x["lines"], "index": x["index"]},
@@ -581,7 +588,7 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
)
)
- def get_objects():
+ def get_objects() -> list[dict[str, object]]:
return list(
map(
lambda x: {"lines": x["lines"], "index": x["index"]},
@@ -600,7 +607,7 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
)
-def get_type_blocks(blocks, block_type: Literal["image", "table", "chart"]):
+def get_type_blocks(blocks: list[Block], block_type: Literal["image", "table", "chart"]) -> list[dict[str, object]]:
with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")
ret = []
for v in with_captions:
@@ -612,7 +619,7 @@ def get_type_blocks(blocks, block_type: Literal["image", "table", "chart"]):
return ret
-def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "chart"]):
+def fix_two_layer_blocks(blocks: list[Block], fix_type: Literal["image", "table", "chart"]) -> list[Block]:
need_fix_blocks = get_type_blocks(blocks, fix_type)
fixed_blocks = []
not_include_blocks = []
@@ -681,7 +688,7 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "chart"]):
return fixed_blocks, not_include_blocks
-def classify_caption_blocks(page_blocks: list) -> list:
+def classify_caption_blocks(page_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
对page_blocks中的caption块进行分类,将其分类为image_caption、table_caption或chart_caption。
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index 2ff33d92..1fd4fe86 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-from mineru.backend.office.mkcontent.inline_renderer import (
+from .mkcontent.inline_renderer import (
display_left_delimiter,
display_right_delimiter,
get_title_level,
@@ -7,7 +7,7 @@ from mineru.backend.office.mkcontent.inline_renderer import (
inline_right_delimiter,
merge_para_with_text,
)
-from mineru.backend.office.mkcontent.output_builders import (
+from .mkcontent.output_builders import (
get_body_data,
make_blocks_to_content_list,
make_blocks_to_content_list_v2,
@@ -19,18 +19,18 @@ from mineru.backend.office.mkcontent.output_builders import (
)
__all__ = [
- 'display_left_delimiter',
- 'display_right_delimiter',
- 'get_body_data',
- 'get_title_level',
- 'inline_left_delimiter',
- 'inline_right_delimiter',
- 'make_blocks_to_content_list',
- 'make_blocks_to_content_list_v2',
- 'merge_index_to_markdown',
- 'merge_list_to_markdown',
- 'merge_para_with_text',
- 'merge_para_with_text_v2',
- 'mk_blocks_to_markdown',
- 'union_make',
+ "display_left_delimiter",
+ "display_right_delimiter",
+ "get_body_data",
+ "get_title_level",
+ "inline_left_delimiter",
+ "inline_right_delimiter",
+ "make_blocks_to_content_list",
+ "make_blocks_to_content_list_v2",
+ "merge_index_to_markdown",
+ "merge_list_to_markdown",
+ "merge_para_with_text",
+ "merge_para_with_text_v2",
+ "mk_blocks_to_markdown",
+ "union_make",
]
diff --git a/mineru/backend/office/pptx_analyze.py b/mineru/backend/office/pptx_analyze.py
index 1e017c32..2f580757 100644
--- a/mineru/backend/office/pptx_analyze.py
+++ b/mineru/backend/office/pptx_analyze.py
@@ -1,14 +1,18 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import time
from io import BytesIO
+from typing import Any
from loguru import logger
+from ...data.data_reader_writer import FileBasedDataWriter
from ...model.pptx.main import convert_binary
from .model_output_to_middle_json import result_to_middle_json
-def office_pptx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
+def office_pptx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict[str, Any]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -18,11 +22,7 @@ def office_pptx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(
- results,
- image_writer,
- )
-
+ middle_json = result_to_middle_json(results, image_writer)
return middle_json, results
@@ -32,6 +32,7 @@ if __name__ == "__main__":
# module is executed. Allow the user to override the path via a
# command-line argument for even greater flexibility.
import argparse
+ import json
from pathlib import Path
script_root = Path(__file__).resolve().parent.parent.parent.parent
@@ -52,7 +53,6 @@ if __name__ == "__main__":
args = parser.parse_args()
pptx_path = Path(args.pptx)
- from mineru.data.data_reader_writer import FileBasedDataWriter
with open(pptx_path, "rb") as f:
file_bytes = f.read()
@@ -62,6 +62,4 @@ if __name__ == "__main__":
image_writer=image_writer,
)
- import json
-
logger.info(json.dumps(middle_json, indent=2, ensure_ascii=False))
diff --git a/mineru/backend/office/xlsx_analyze.py b/mineru/backend/office/xlsx_analyze.py
index 476feb63..155deaf8 100644
--- a/mineru/backend/office/xlsx_analyze.py
+++ b/mineru/backend/office/xlsx_analyze.py
@@ -1,14 +1,18 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import time
from io import BytesIO
+from typing import Any
from loguru import logger
+from ...data.data_reader_writer import FileBasedDataWriter
from ...model.xlsx.main import convert_binary
from .model_output_to_middle_json import result_to_middle_json
-def office_xlsx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
+def office_xlsx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict[str, Any]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -18,11 +22,7 @@ def office_xlsx_analyze(file_bytes: bytes, image_writer: Any = None) -> dict:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(
- results,
- image_writer,
- )
-
+ middle_json = result_to_middle_json(results, image_writer)
return middle_json, results
@@ -32,6 +32,7 @@ if __name__ == "__main__":
# module is executed. Allow the user to override the path via a
# command-line argument for even greater flexibility.
import argparse
+ import json
from pathlib import Path
script_root = Path(__file__).resolve().parent.parent.parent.parent
@@ -52,7 +53,6 @@ if __name__ == "__main__":
args = parser.parse_args()
xlsx_path = Path(args.xlsx)
- from mineru.data.data_reader_writer import FileBasedDataWriter
with open(xlsx_path, "rb") as f:
file_bytes = f.read()
@@ -62,6 +62,4 @@ if __name__ == "__main__":
image_writer=image_writer,
)
- import json
-
logger.info(json.dumps(middle_json, indent=2, ensure_ascii=False))
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
index be8f9808..a9f71959 100644
--- a/mineru/backend/pipeline/batch_analyze.py
+++ b/mineru/backend/pipeline/batch_analyze.py
@@ -1,9 +1,14 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import base64
import html
import re
+from typing import Any
import cv2
+import numpy as np
+from PIL import Image
from loguru import logger
from tqdm import tqdm
from collections import defaultdict
@@ -16,6 +21,7 @@ from .model_init import (
run_ocr_det_inference,
run_ocr_rec_inference,
)
+from .pipeline_analyze import ModelSingleton
from .model_list import AtomicModel
from ...utils.config_reader import (
get_formula_enable,
@@ -50,15 +56,15 @@ TABLE_OCR_REC_REGEX_REPLACEMENTS = (
class BatchAnalyze:
def __init__(
self,
- model_manager,
+ model_manager: ModelSingleton,
batch_ratio: int,
- formula_enable,
- table_enable,
+ formula_enable: bool,
+ table_enable: bool,
enable_ocr_det_batch: bool = True,
table_ori_cls_batch_enabled: bool | None = None,
text_ocr_det_batch_enabled: bool | None = None,
mask_inline_formula_for_ocr_det: bool = True,
- ):
+ ) -> None:
self.batch_ratio = batch_ratio
self.formula_enable = get_formula_enable(formula_enable)
self.table_enable = get_table_enable(table_enable)
@@ -112,7 +118,7 @@ class BatchAnalyze:
if not ocr_enable or not layout_res:
return
- def keep_item(item: dict) -> bool:
+ def keep_item(item: dict[str, Any]) -> bool:
if item.get("label") != "ocr_text":
return True
@@ -198,11 +204,11 @@ class BatchAnalyze:
]
@staticmethod
- def _table_supports_inline_objects(table_res_dict: dict) -> bool:
+ def _table_supports_inline_objects(table_res_dict: dict[str, Any]) -> bool:
return str(table_res_dict.get("rotate_label", "0")) == "0"
@staticmethod
- def _apply_table_rotate_label(table_res_dict: dict, rotate_label: str) -> None:
+ def _apply_table_rotate_label(table_res_dict: dict[str, Any], rotate_label: str) -> None:
"""根据方向预测结果写回标签,并同步旋转无线和有线表格图片。"""
rotate_label = str(rotate_label or "0")
table_res_dict["rotate_label"] = rotate_label
@@ -350,7 +356,7 @@ class BatchAnalyze:
return table_inline_objects
- def __call__(self, images_with_extra_info: list) -> list:
+ 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 []
@@ -440,7 +446,7 @@ class BatchAnalyze:
})
for table_res in table_res_list:
- def get_crop_table_img(scale):
+ def get_crop_table_img(scale: float) -> Image.Image:
bbox = normalize_to_int_bbox(
[float(v) / float(scale) for v in table_res["bbox"]]
)
diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.py
index 3c05859d..9620d5ea 100644
--- a/mineru/backend/pipeline/model_init.py
+++ b/mineru/backend/pipeline/model_init.py
@@ -1,6 +1,10 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import os
import threading
+from collections.abc import Callable
+from typing import Any
import torch
from loguru import logger
@@ -28,7 +32,9 @@ PIPELINE_OCR_REC_INFERENCE_LOCK = threading.RLock()
PIPELINE_INFERENCE_LOCKS_ENABLED = os.getenv("MINERU_ENABLE_PIPELINE_INFERENCE_LOCKS", "False").lower() in ["true", "1", "yes"]
-def _run_with_inference_lock(inference_lock, inference_callable, *args, **kwargs):
+def _run_with_inference_lock(
+ inference_lock: threading.RLock, inference_callable: Callable[..., Any], *args: Any, **kwargs: Any
+) -> object:
"""按实验开关决定是否在指定推理锁内执行真实 native 模型调用。"""
if not PIPELINE_INFERENCE_LOCKS_ENABLED:
return inference_callable(*args, **kwargs)
@@ -37,22 +43,22 @@ def _run_with_inference_lock(inference_lock, inference_callable, *args, **kwargs
return inference_callable(*args, **kwargs)
-def run_layout_inference(inference_callable, *args, **kwargs):
+def run_layout_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 Layout 模型调用。"""
return _run_with_inference_lock(PIPELINE_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs)
-def run_mfr_inference(inference_callable, *args, **kwargs):
+def run_mfr_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 MFR 模型调用。"""
return _run_with_inference_lock(PIPELINE_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
-def run_ocr_det_inference(inference_callable, *args, **kwargs):
+def run_ocr_det_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 OCR det 模型调用。"""
return _run_with_inference_lock(PIPELINE_OCR_DET_INFERENCE_LOCK, inference_callable, *args, **kwargs)
-def run_ocr_rec_inference(inference_callable, *args, **kwargs):
+def run_ocr_rec_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 OCR rec 模型调用。"""
return _run_with_inference_lock(PIPELINE_OCR_REC_INFERENCE_LOCK, inference_callable, *args, **kwargs)
@@ -67,7 +73,7 @@ else:
MFR_MODEL = "unimernet_small"
-def table_orientation_cls_model_init():
+def table_orientation_cls_model_init() -> MineruTableOrientationClsModel:
atom_model_manager = AtomModelSingleton()
ocr_engine = atom_model_manager.get_atom_model(
atom_model_name=AtomicModel.OCR,
@@ -80,11 +86,11 @@ def table_orientation_cls_model_init():
return cls_model
-def table_cls_model_init():
+def table_cls_model_init() -> PaddleTableClsModel:
return PaddleTableClsModel()
-def wired_table_model_init(lang: str | None = None) -> Any:
+def wired_table_model_init(lang: str | None = None) -> UnetTableModel:
atom_model_manager = AtomModelSingleton()
ocr_engine = atom_model_manager.get_atom_model(
atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False
@@ -93,7 +99,7 @@ def wired_table_model_init(lang: str | None = None) -> Any:
return table_model
-def wireless_table_model_init(lang: str | None = None) -> Any:
+def wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:
atom_model_manager = AtomModelSingleton()
ocr_engine = atom_model_manager.get_atom_model(
atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False
@@ -102,7 +108,7 @@ def wireless_table_model_init(lang: str | None = None) -> Any:
return table_model
-def mfr_model_init(weight_dir: str, device: str = "cpu") -> Any:
+def mfr_model_init(weight_dir: str, device: str = "cpu") -> UnimernetModel | FormulaRecognizer:
if MFR_MODEL == "unimernet_small":
mfr_model = UnimernetModel(weight_dir, device)
elif MFR_MODEL == "pp_formulanet_plus_m":
@@ -113,15 +119,19 @@ def mfr_model_init(weight_dir: str, device: str = "cpu") -> Any:
return mfr_model
-def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> Any:
+def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> PPDocLayoutV2LayoutModel:
if str(device).startswith("npu"):
device = torch.device(device)
model = PPDocLayoutV2LayoutModel(weight, device)
return model
-def ocr_model_init(det_db_box_thresh: float = 0.5, lang: str | None = None, det_db_unclip_ratio: float = 1.5, enable_merge_det_boxes: bool = True) -> Any:
-
+def ocr_model_init(
+ det_db_box_thresh: float = 0.5,
+ lang: str | None = None,
+ det_db_unclip_ratio: float = 1.5,
+ enable_merge_det_boxes: bool = True,
+) -> PytorchPaddleOCR:
if lang in [None, "ch"]:
use_dilation = True
det_db_unclip_ratio = 1.8
@@ -147,18 +157,17 @@ def ocr_model_init(det_db_box_thresh: float = 0.5, lang: str | None = None, det_
class AtomModelSingleton:
- _instance = None
- _models = {}
- _lock = PIPELINE_MODEL_INIT_LOCK
+ _instance: AtomModelSingleton | None = None
+ _models: dict[object, object] = {}
+ _lock: threading.RLock = PIPELINE_MODEL_INIT_LOCK
- def __new__(cls, *args, **kwargs):
+ def __new__(cls, *args: Any, **kwargs: Any) -> AtomModelSingleton:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
- def get_atom_model(self, atom_model_name: str, **kwargs):
-
+ def get_atom_model(self, atom_model_name: str, **kwargs: Any) -> Any:
lang = kwargs.get("lang", None)
if atom_model_name in [AtomicModel.WiredTable, AtomicModel.WirelessTable]:
@@ -222,22 +231,22 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
class MineruPipelineModel:
- def __init__(self, **kwargs):
- self.formula_config = kwargs.get("formula_config")
- self.apply_formula = self.formula_config.get("enable", True)
- self.table_config = kwargs.get("table_config")
- self.apply_table = self.table_config.get("enable", True)
- self.lang = kwargs.get("lang", None)
- self.device = kwargs.get("device", "cpu")
+ def __init__(self, **kwargs: Any) -> None:
+ self.formula_config: dict[str, Any] = kwargs.get("formula_config", {})
+ self.apply_formula: bool = self.formula_config.get("enable", True)
+ self.table_config: dict[str, Any] = kwargs.get("table_config", {})
+ self.apply_table: bool = self.table_config.get("enable", True)
+ self.lang: str | None = kwargs.get("lang", None)
+ self.device: str = kwargs.get("device", "cpu")
logger.info("DocAnalysis init, this may take some times......")
atom_model_manager = AtomModelSingleton()
if self.apply_formula:
# 初始化公式解析模型
if MFR_MODEL == "unimernet_small":
- mfr_model_path = ModelPath.unimernet_small
+ mfr_model_path: str = ModelPath.unimernet_small
elif MFR_MODEL == "pp_formulanet_plus_m":
- mfr_model_path = ModelPath.pp_formulanet_plus_m
+ mfr_model_path: str = ModelPath.pp_formulanet_plus_m
else:
logger.error("MFR model name not allow")
exit(1)
@@ -280,11 +289,11 @@ class MineruPipelineModel:
class HybridModelSingleton:
- _instance = None
- _models = {}
- _lock = PIPELINE_MODEL_INIT_LOCK
+ _instance: HybridModelSingleton | None = None
+ _models: dict[object, object] = {}
+ _lock: threading.RLock = PIPELINE_MODEL_INIT_LOCK
- def __new__(cls, *args, **kwargs):
+ def __new__(cls, *args: Any, **kwargs: Any) -> HybridModelSingleton:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
@@ -292,9 +301,9 @@ class HybridModelSingleton:
def get_model(
self,
- lang=None,
- formula_enable=None,
- ):
+ lang: str | None = None,
+ formula_enable: bool | None = None,
+ ) -> MineruHybridModel:
key = (lang, formula_enable)
with self._lock:
if key not in self._models:
@@ -305,15 +314,15 @@ class HybridModelSingleton:
return self._models[key]
-def ocr_det_batch_setting():
- import torch
+def ocr_det_batch_setting() -> bool:
+ import torch as _torch
from packaging import version
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
if device_type.lower() in ["corex"]:
enable_ocr_det_batch = False
else:
- if version.parse(torch.__version__) >= version.parse("2.8.0"):
+ if version.parse(_torch.__version__) >= version.parse("2.8.0"):
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
enable_ocr_det_batch = True
@@ -323,18 +332,18 @@ def ocr_det_batch_setting():
class MineruHybridModel:
def __init__(
self,
- device=None,
- lang=None,
- formula_enable=True,
- ):
+ device: str | None = None,
+ lang: str | None = None,
+ formula_enable: bool = True,
+ ) -> None:
if device is not None:
- self.device = device
+ self.device: str = device
else:
- self.device = get_device()
+ self.device: str = get_device()
- self.lang = lang
+ self.lang: str | None = lang
- self.enable_ocr_det_batch = ocr_det_batch_setting()
+ self.enable_ocr_det_batch: bool = ocr_det_batch_setting()
if str(self.device).startswith("npu"):
try:
@@ -368,9 +377,9 @@ class MineruHybridModel:
if formula_enable:
# 初始化公式解析模型
if MFR_MODEL == "unimernet_small":
- mfr_model_path = ModelPath.unimernet_small
+ mfr_model_path: str = ModelPath.unimernet_small
elif MFR_MODEL == "pp_formulanet_plus_m":
- mfr_model_path = ModelPath.pp_formulanet_plus_m
+ mfr_model_path: str = ModelPath.pp_formulanet_plus_m
else:
logger.error("MFR model name not allow")
exit(1)
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 7b0cb542..57ac9a54 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -1,7 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
from typing import Any
-from ...types import PageInfo
+from ...data.data_reader_writer import DataWriter
+from ...types import Block, PageInfo, Span
from ...utils.char_utils import full_to_half
from ...utils.cut_image import cut_image_and_table
from ...utils.enum_class import BlockType, ContentType
@@ -10,6 +11,7 @@ from ...utils.pdfium_guard import pdfium_guard
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ...version import __version__
from ..utils.html_image_utils import replace_inline_table_images
+from ..utils.middle_json_utils import append_pages, apply_post_ocr, build_middle_json
from ..utils.runtime_utils import cross_page_table_merge
from .model_init import AtomModelSingleton
from .para_split import para_split
@@ -17,7 +19,12 @@ from .pipeline_magic_model import MagicModel
def blocks_to_page_info(
- page_model_info: dict, image_dict: dict, page: Any, image_writer: Any, page_index: int, ocr_enable: bool = False
+ page_model_info: dict[str, Any],
+ image_dict: dict[str, Any],
+ page: Any,
+ image_writer: DataWriter,
+ page_index: int,
+ ocr_enable: bool = False,
) -> PageInfo:
scale = image_dict["scale"]
page_pil_img = image_dict["img_pil"]
@@ -33,7 +40,7 @@ def blocks_to_page_info(
# 对image/table/chart/interline_equation的span截图
for span in all_image_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)
"""构造page_info"""
@@ -41,27 +48,29 @@ def blocks_to_page_info(
page_info = make_page_info_dict(
preproc_blocks,
- page_index, page_w, page_h,
+ page_index,
+ page_w,
+ page_h,
discarded_blocks,
)
return page_info
-def build_page_model_info(page_layout_dets: list, page_index: int, pil_img: Any) -> dict:
+def build_page_model_info(page_layout_dets: list[dict[str, Any]], page_index: int, pil_img: Any) -> dict[str, Any]:
page_info_dict = {"page_no": page_index, "width": pil_img.width, "height": pil_img.height}
return {"layout_dets": page_layout_dets, "page_info": page_info_dict}
def append_batch_results_to_middle_json(
- middle_json: dict,
- batch_results: list,
- images_list: list,
+ middle_json: dict[str, Any],
+ batch_results: list[list[dict[str, Any]]],
+ images_list: list[dict[str, Any]],
pdf_doc: Any,
- image_writer: Any,
+ image_writer: DataWriter,
page_start_index: int = 0,
ocr_enable: bool = False,
- model_list: list | None = None,
+ model_list: list[dict[str, Any]] | None = None,
progress_bar: Any = None,
) -> None:
page_model_infos = []
@@ -73,8 +82,6 @@ def append_batch_results_to_middle_json(
if model_list is not None:
model_list.extend(page_model_infos)
- from mineru.backend.utils.middle_json_utils import append_pages
-
append_pages(
middle_json,
page_model_infos,
@@ -90,8 +97,8 @@ def append_batch_results_to_middle_json(
def _extract_text_from_block(block: Block) -> str:
text_parts = []
- for line in block.get("lines", []):
- for span in line.get("spans", []):
+ for line in block.lines:
+ for span in line.spans:
if span.get("type") == ContentType.TEXT:
text_parts.append(span.get("content", ""))
return "".join(text_parts).strip()
@@ -107,8 +114,8 @@ def _normalize_formula_tag_content(tag_content: str) -> str:
def _get_interline_equation_span(block: Block) -> Span | None:
- for line in block.get("lines", []):
- for span in line.get("spans", []):
+ for line in block.lines:
+ for span in line.spans:
if span.get("type") == ContentType.INTERLINE_EQUATION:
return span
return None
@@ -153,8 +160,6 @@ def _optimize_formula_number_blocks(pdf_info_list: list[PageInfo]) -> None:
def _apply_post_ocr(pdf_info_list: list[PageInfo], lang: str | None = None) -> None:
- from mineru.backend.utils.middle_json_utils import apply_post_ocr
-
atom_model_manager = AtomModelSingleton()
ocr_model = atom_model_manager.get_atom_model(
atom_model_name="ocr",
@@ -202,13 +207,19 @@ def finalize_middle_json(
finalize_middle_json_from_preproc(pdf_info_list)
-def init_middle_json() -> dict:
+def init_middle_json() -> dict[str, Any]:
return {"pdf_info": [], "_backend": "pipeline", "_version_name": __version__}
-def result_to_middle_json(model_list: list, images_list: list, pdf_doc: Any, image_writer: Any, lang: str | None = None, ocr_enable: bool = False, formula_enable: bool | None = None) -> dict:
- from mineru.backend.utils.middle_json_utils import build_middle_json
-
+def result_to_middle_json(
+ model_list: list[list[dict[str, Any]]],
+ images_list: list[dict[str, Any]],
+ pdf_doc: Any,
+ image_writer: DataWriter,
+ lang: str | None = None,
+ ocr_enable: bool = False,
+ formula_enable: bool | None = None,
+) -> dict[str, Any]:
return build_middle_json(
model_list,
images_list,
@@ -222,7 +233,7 @@ def result_to_middle_json(model_list: list, images_list: list, pdf_doc: Any, ima
)
-def make_page_info_dict(blocks: list, page_id: int, page_w: int, page_h: int, discarded_blocks: list) -> PageInfo:
+def make_page_info_dict(blocks: list[Block], page_id: int, page_w: int, page_h: int, discarded_blocks: list[Block]) -> PageInfo:
return PageInfo(
preproc_blocks=blocks,
page_idx=page_id,
diff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.py
index ba33ea53..a5fb8d97 100644
--- a/mineru/backend/pipeline/para_split.py
+++ b/mineru/backend/pipeline/para_split.py
@@ -1,17 +1,19 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import copy
-from loguru import logger
-from mineru.utils.enum_class import ContentType, BlockType, SplitFlag
-from mineru.utils.language import detect_lang
+from ...types import Block, PageInfo
+from ...utils.enum_class import BlockType, ContentType, SplitFlag
+from ...utils.language import detect_lang
-LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';')
-LIST_END_FLAG = ('.', '。', ';', ';')
+LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")
+LIST_END_FLAG = (".", "。", ";", ";")
class ListLineTag:
- IS_LIST_START_LINE = 'is_list_start_line'
- IS_LIST_END_LINE = 'is_list_end_line'
+ IS_LIST_START_LINE = "is_list_start_line"
+ IS_LIST_END_LINE = "is_list_end_line"
def __process_blocks(blocks: list[Block]) -> list[Block]:
@@ -26,14 +28,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:
- 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']]),
+ 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:
+ 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"]]),
]
current_group.append(current_block)
@@ -41,7 +43,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,
@@ -58,10 +60,10 @@ def __process_blocks(blocks: list[Block]) -> list[Block]:
def __is_list_or_index_block(block: Block) -> bool:
- if block['type'] == BlockType.VERTICAL_TEXT:
+ if block["type"] == BlockType.VERTICAL_TEXT:
return BlockType.VERTICAL_TEXT
- if block['type'] == BlockType.INDEX:
- for line in block['lines']:
+ if block["type"] == BlockType.INDEX:
+ for line in block["lines"]:
line[ListLineTag.IS_LIST_START_LINE] = True
return BlockType.INDEX
# 一个block如果是list block 应该同时满足以下特征
@@ -72,12 +74,12 @@ 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]
- 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']
+ 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"]
left_close_num = 0
left_not_close_num = 0
@@ -87,7 +89,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
@@ -97,51 +99,51 @@ 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 = ''
+ block_text = ""
- for line in block['lines']:
- line_text = ''
+ 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)
+ block_text = "".join(lines_text_list)
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
- block_mid_x = (block['bbox_fs'][0] + block['bbox_fs'][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:
# 类中文没有超长单词的情况,可以用统一的阈值
- if block_lang in ['zh', 'ja', 'ko']:
+ if block_lang in ["zh", "ja", "ko"]:
closed_area = 0.26 * block_weight
else:
# 右侧不顶格情况下是否有一段距离,拍脑袋用0.3block宽度做阈值
@@ -150,7 +152,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结尾
@@ -171,20 +173,14 @@ def __is_list_or_index_block(block: Block) -> bool:
if line_text[-1].isdigit():
num_end_count += 1
- if (
- num_start_count / len(lines_text_list) >= 0.8
- or num_end_count / len(lines_text_list) >= 0.8
- ):
+ if num_start_count / len(lines_text_list) >= 0.8 or num_end_count / len(lines_text_list) >= 0.8:
line_num_flag = True
if flag_end_count / len(lines_text_list) >= 0.8:
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']:
+ 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
return BlockType.INDEX
@@ -192,11 +188,11 @@ def __is_list_or_index_block(block: Block) -> bool:
# 补充条件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']:
+ for line in block["lines"]:
line[ListLineTag.IS_LIST_START_LINE] = True
return BlockType.LIST
@@ -207,41 +203,33 @@ 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:
+ 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
# 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
elif line_end_flag:
- for i, line in enumerate(block['lines']):
- if (
- len(lines_text_list[i]) > 0
- and lines_text_list[i][-1] in LIST_END_FLAG
- ):
+ 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
+ if i + 1 < len(block["lines"]):
+ block["lines"][i + 1][ListLineTag.IS_LIST_START_LINE] = 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_start_flag = False
- if (
- abs(block['bbox_fs'][2] - line['bbox'][2])
- > 0.1 * block_weight
- ):
+ if abs(block["bbox_fs"][2] - line["bbox"][2]) > 0.1 * block_weight:
line[ListLineTag.IS_LIST_END_LINE] = 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
@@ -249,10 +237,10 @@ def __is_list_or_index_block(block: Block) -> bool:
line[ListLineTag.IS_LIST_END_LINE] = True
else:
# 正常有缩进的list处理
- for line in block['lines']:
- if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
+ 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:
+ if abs(block["bbox_fs"][2] - line["bbox"][2]) > line_height:
line[ListLineTag.IS_LIST_END_LINE] = True
return BlockType.LIST
@@ -263,27 +251,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的第一个字符是数字
@@ -291,65 +279,65 @@ 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']:
+ 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'] = []
+ block2["lines"].extend(block1["lines"])
+ block1["lines"] = []
block1[SplitFlag.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]
- first_content = first_span.get('content', '')
- last_content = last_span.get('content', '')
+ 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']:
+ 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'] = []
+ block2["lines"].extend(block1["lines"])
+ block1["lines"] = []
block1[SplitFlag.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']:
+ 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'] = []
+ block2["lines"].extend(block1["lines"])
+ block1["lines"] = []
block1[SplitFlag.LINES_DELETED] = True
return block1, block2
@@ -359,9 +347,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
@@ -373,7 +361,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:
@@ -388,23 +376,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)
@@ -415,29 +392,29 @@ def __para_merge_page(blocks: list[Block]) -> list[Block]:
def para_split(page_info_list: list[PageInfo]) -> None:
all_blocks = []
for page_info in page_info_list:
- blocks = copy.deepcopy(page_info['preproc_blocks'])
+ blocks = copy.deepcopy(page_info["preproc_blocks"])
for block in blocks:
- block['page_num'] = page_info['page_idx']
- block['page_size'] = page_info['page_size']
+ block["page_num"] = page_info["page_idx"]
+ block["page_size"] = page_info["page_size"]
all_blocks.extend(blocks)
__para_merge_page(all_blocks)
for page_info in page_info_list:
- page_info['para_blocks'] = []
+ page_info["para_blocks"] = []
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
- page_info['para_blocks'].append(block)
+ if "page_num" in block:
+ if block["page_num"] == page_info["page_idx"]:
+ 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']
- del block['page_size']
+ del block["page_num"]
+ del block["page_size"]
-if __name__ == '__main__':
+if __name__ == "__main__":
input_blocks = []
# 调用函数
groups = __process_blocks(input_blocks)
for group_index, group in enumerate(groups):
- print(f'Group {group_index}: {group}')
+ print(f"Group {group_index}: {group}")
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index 71a1af91..63ab8ade 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -1,7 +1,10 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import os
import time
-from typing import List, Tuple
+from collections.abc import Callable
+from typing import Any, List, Tuple
import pypdfium2 as pdfium
from loguru import logger
@@ -31,7 +34,7 @@ class ModelSingleton:
_models = {}
_lock = PIPELINE_MODEL_INIT_LOCK
- def __new__(cls, *args, **kwargs):
+ def __new__(cls, *args: Any, **kwargs: Any) -> ModelSingleton:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
@@ -39,10 +42,10 @@ class ModelSingleton:
def get_model(
self,
- lang=None,
- formula_enable=None,
- table_enable=None,
- ):
+ lang: str | None = None,
+ formula_enable: bool | None = None,
+ table_enable: bool | None = None,
+ ) -> MineruPipelineModel:
key = (lang, formula_enable, table_enable)
with self._lock:
if key not in self._models:
@@ -55,10 +58,10 @@ class ModelSingleton:
def custom_model_init(
- lang=None,
- formula_enable=True,
- table_enable=True,
-):
+ lang: str | None = None,
+ formula_enable: bool = True,
+ table_enable: bool = True,
+) -> MineruPipelineModel:
model_init_start = time.time()
# 从配置文件读取model-dir和device
device = get_device()
@@ -81,7 +84,7 @@ def custom_model_init(
return custom_model
-def _get_ocr_enable(pdf_bytes, parse_method: str) -> bool:
+def _get_ocr_enable(pdf_bytes: bytes, parse_method: str) -> bool:
if parse_method == "auto":
return classify(pdf_bytes) == "ocr"
if parse_method == "ocr":
@@ -89,7 +92,7 @@ def _get_ocr_enable(pdf_bytes, parse_method: str) -> bool:
return False
-def _close_images(images_list: list) -> None:
+def _close_images(images_list: list[dict[str, Any]]) -> None:
for image_dict in images_list or []:
pil_img = image_dict.get("img_pil")
if pil_img is not None:
@@ -99,15 +102,15 @@ def _close_images(images_list: list) -> None:
pass
-def _format_doc_slices(batch_slices: list) -> list:
+def _format_doc_slices(batch_slices: list[dict[str, int]]) -> str:
return ",".join(f"doc{item['doc_index']}:{item['page_start'] + 1}-{item['page_end'] + 1}" for item in batch_slices)
def _finalize_processing_window_context(
- context,
- on_doc_ready,
- client_side_output_generation=False,
-):
+ context: dict[str, object],
+ on_doc_ready: Callable[..., object],
+ client_side_output_generation: bool = False,
+) -> None:
if context["closed"]:
return
if client_side_output_generation:
@@ -132,10 +135,10 @@ def _finalize_processing_window_context(
def _emit_zero_page_contexts(
- doc_contexts,
- on_doc_ready,
- client_side_output_generation=False,
-):
+ doc_contexts: list[dict[str, object]],
+ on_doc_ready: Callable[..., object],
+ client_side_output_generation: bool = False,
+) -> None:
for context in doc_contexts:
if context["page_count"] == 0 and not context["closed"]:
_finalize_processing_window_context(
@@ -146,15 +149,15 @@ def _emit_zero_page_contexts(
def doc_analyze_streaming(
- pdf_bytes_list,
- image_writer_list,
- lang_list,
- on_doc_ready,
+ pdf_bytes_list: list[bytes],
+ image_writer_list: list[object],
+ lang_list: list[str | None],
+ on_doc_ready: Callable[..., object],
parse_method: str = "auto",
- formula_enable=True,
- table_enable=True,
- client_side_output_generation=False,
-):
+ formula_enable: bool = True,
+ table_enable: bool = True,
+ client_side_output_generation: bool = False,
+) -> None:
if not (len(pdf_bytes_list) == len(image_writer_list) == len(lang_list)):
raise ValueError("pdf_bytes_list, image_writer_list, and lang_list must have the same length")
@@ -316,7 +319,11 @@ def doc_analyze_streaming(
context["closed"] = True
-def batch_image_analyze(images_with_extra_info: List[Tuple[Image.Image, bool, str]], formula_enable=True, table_enable=True):
+def batch_image_analyze(
+ images_with_extra_info: List[Tuple[Image.Image, bool, str]],
+ formula_enable: bool = True,
+ table_enable: bool = True,
+) -> object:
from .batch_analyze import BatchAnalyze
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 3e718c10..68ca5b5b 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -1,4 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
from ...types import Block, Line, Span
from ...utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
from ...utils.enum_class import BlockType, ContentType
@@ -19,9 +23,12 @@ from ...utils.visual_magic_model_utils import (
from .para_split import ListLineTag
from .pipeline_middle_json_mkcontent import _merge_para_text
+if TYPE_CHECKING:
+ from PIL.Image import Image as PILImage
+
class MagicModel:
- PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES = {
+ PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES: dict[str, str] = {
"abstract": BlockType.ABSTRACT,
"algorithm": BlockType.CODE,
"aside_text": BlockType.ASIDE_TEXT,
@@ -47,9 +54,9 @@ class MagicModel:
"vision_footnote": BlockType.FOOTNOTE,
}
- VISUAL_MAIN_TYPES = (BlockType.IMAGE, BlockType.TABLE, BlockType.CHART, BlockType.CODE)
- VISUAL_CHILD_TYPES = (BlockType.CAPTION, BlockType.FOOTNOTE)
- VISUAL_TYPE_MAPPING = {
+ VISUAL_MAIN_TYPES: tuple[str, ...] = (BlockType.IMAGE, BlockType.TABLE, BlockType.CHART, BlockType.CODE)
+ VISUAL_CHILD_TYPES: tuple[str, ...] = (BlockType.CAPTION, BlockType.FOOTNOTE)
+ VISUAL_TYPE_MAPPING: dict[str, dict[str, str]] = {
BlockType.IMAGE: {
"body": BlockType.IMAGE_BODY,
"caption": BlockType.IMAGE_CAPTION,
@@ -74,23 +81,23 @@ class MagicModel:
def __init__(
self,
- page_model_info: dict,
- page=None,
- scale=1,
- page_pil_img=None,
- page_w=None,
- page_h=None,
- ocr_enable=False,
- ):
+ page_model_info: dict[str, Any],
+ page: object = None,
+ scale: float = 1,
+ page_pil_img: PILImage | None = None,
+ page_w: int = 0,
+ page_h: int = 0,
+ ocr_enable: bool = False,
+ ) -> None:
self.__page_model_info = page_model_info
- self.page_inline_formula = []
- self.page_ocr_res = []
- self.page_blocks = []
- self.image_groups = []
- self.table_groups = []
- self.chart_groups = []
- self.all_image_spans = []
- self.__layout_det_by_index = {}
+ self.page_inline_formula: list[Span] = []
+ self.page_ocr_res: list[Span] = []
+ self.page_blocks: list[Block] = []
+ self.image_groups: list[dict[str, Any]] = []
+ self.table_groups: list[dict[str, Any]] = []
+ self.chart_groups: list[dict[str, Any]] = []
+ self.all_image_spans: list[Span] = []
+ self.__layout_det_by_index: dict[int, dict[str, Any]] = {}
self.__scale = scale
self.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spans
self.__post_process() # index重排,填充行内公式和文本span
@@ -131,7 +138,7 @@ class MagicModel:
self.__build_return_blocks()
@staticmethod
- def __fix_text_block(block):
+ def __fix_text_block(block: Block) -> Block:
if block["type"] == BlockType.TEXT and is_vertical_text_block_by_spans(block["spans"]):
# layout 偶发会把竖排正文识别为横排 text,这里用旧版 span 高宽比规则兜底。
block["type"] = BlockType.VERTICAL_TEXT
@@ -158,7 +165,7 @@ class MagicModel:
return block
@staticmethod
- def __copy_block_fields(block, **overrides):
+ def __copy_block_fields(block: dict[str, Any], **overrides: Any) -> Block:
extra = {k: v for k, v in block.items() if k not in {"cls_id", "label"} and k not in Block.__dataclass_fields__}
return Block(
type=overrides.pop("type", block.get("type", "")),
@@ -167,20 +174,20 @@ class MagicModel:
)
@staticmethod
- def __is_inline_formula_block(layout_det: dict) -> bool:
+ def __is_inline_formula_block(layout_det: dict[str, Any]) -> bool:
return layout_det.get("label") == "inline_formula" or layout_det.get("cls_id") == 15
@staticmethod
- def __is_ocr_text_block(layout_det: dict) -> bool:
+ def __is_ocr_text_block(layout_det: dict[str, Any]) -> bool:
return layout_det.get("label") == "ocr_text"
@staticmethod
- def __is_seal_layout_block(layout_det: dict) -> bool:
+ def __is_seal_layout_block(layout_det: dict[str, Any]) -> bool:
"""判断原始 layout 是否为印章,输出层会将其规范为 image 子类型。"""
return layout_det.get("label") == "seal"
@staticmethod
- def __normalize_seal_text(content):
+ def __normalize_seal_text(content: str | list[str]) -> str:
"""将 seal OCR 的列表或字符串结果规范为 VLM 一致的多行字符串。"""
if isinstance(content, list):
return "\n".join(str(item) for item in content if str(item).strip())
@@ -188,11 +195,11 @@ class MagicModel:
return content.strip()
return ""
- def __build_return_blocks(self):
- self.preproc_blocks = []
- self.discarded_blocks = []
+ def __build_return_blocks(self) -> None:
+ self.preproc_blocks: list[Block] = []
+ self.discarded_blocks: list[Block] = []
for block in self.page_blocks:
- if block["type"] in [
+ if block.type in [
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
@@ -202,20 +209,20 @@ class MagicModel:
self.discarded_blocks.append(block)
else:
# 单独处理code block
- if block["type"] in [BlockType.CODE]:
- for sub_block in block["blocks"]:
- if sub_block["type"] == BlockType.CODE_BODY:
+ if block.type in [BlockType.CODE]:
+ for sub_block in block.blocks:
+ if sub_block.type == BlockType.CODE_BODY:
block["sub_type"] = sub_block.pop("sub_type", "algorithm")
if block["sub_type"] == "code":
block["guess_lang"] = sub_block.pop("guess_lang", "txt")
self.preproc_blocks.append(block)
- def __build_page_blocks(self):
+ def __build_page_blocks(self) -> None:
span_type = "unknown"
span_matcher = SpanBlockMatcher(self.page_text_inline_formula_spans)
for block in self.page_blocks:
- if block["type"] in [
+ if block.type in [
BlockType.ABSTRACT,
BlockType.CODE,
BlockType.ASIDE_TEXT,
@@ -234,13 +241,13 @@ class MagicModel:
BlockType.FOOTNOTE,
]:
span_type = ContentType.TEXT
- elif block["type"] in [BlockType.IMAGE]:
+ elif block.type in [BlockType.IMAGE]:
span_type = ContentType.IMAGE
- elif block["type"] in [BlockType.TABLE]:
+ elif block.type in [BlockType.TABLE]:
span_type = ContentType.TABLE
- elif block["type"] in [BlockType.CHART]:
+ elif block.type in [BlockType.CHART]:
span_type = ContentType.CHART
- elif block["type"] in [BlockType.INTERLINE_EQUATION]:
+ elif block.type in [BlockType.INTERLINE_EQUATION]:
span_type = ContentType.INTERLINE_EQUATION
if span_type in [
@@ -265,8 +272,7 @@ class MagicModel:
self.all_image_spans.append(span)
# 构造line对象
spans = [span]
- line = Line(spans=spans)
- line["bbox"] = block["bbox"]
+ line = Line(spans=spans, bbox=block["bbox"])
block["lines"] = [line]
else:
# span填充
@@ -283,15 +289,15 @@ class MagicModel:
self.page_text_inline_formula_spans = span_matcher.remaining_spans()
@staticmethod
- def __formula_number_overlap_ratio(span, block_bbox):
+ def __formula_number_overlap_ratio(span: Span, block_bbox: list[float]) -> float:
"""公式编号框较窄时,沿用最小框重叠比例提高回填召回。"""
return max(
calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block_bbox),
calculate_overlap_area_2_minbox_area_ratio(span["bbox"], block_bbox),
)
- def __fix_axis(self):
- need_remove_list = []
+ def __fix_axis(self) -> None:
+ need_remove_list: list[dict[str, Any]] = []
layout_dets = self.__page_model_info["layout_dets"]
for layout_det in layout_dets:
x0, y0, x1, y1 = layout_det["bbox"]
@@ -308,7 +314,7 @@ class MagicModel:
for need_remove in need_remove_list:
layout_dets.remove(need_remove)
- def __post_process(self):
+ def __post_process(self) -> None:
next_index = 1
layout_dets = self.__page_model_info["layout_dets"]
for layout_det in layout_dets:
@@ -339,7 +345,7 @@ class MagicModel:
layout_det["index"] = next_index
next_index += 1
- def __classify_visual_blocks(self):
+ def __classify_visual_blocks(self) -> None:
if not self.page_blocks:
return
@@ -349,8 +355,10 @@ class MagicModel:
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 = {}
- grouped_children = {main_block["index"]: {"captions": [], "footnotes": []} for main_block in main_blocks}
+ 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
+ }
for child_block in child_blocks:
parent_block = self.__find_best_visual_parent(
@@ -382,7 +390,7 @@ class MagicModel:
self.table_groups = []
self.chart_groups = []
- rebuilt_page_blocks = []
+ rebuilt_page_blocks: list[Block] = []
for block in ordered_blocks:
original_block_type = original_type_by_index[block["index"]]
@@ -446,12 +454,12 @@ class MagicModel:
def __find_best_visual_parent(
self,
- child_block,
- main_blocks,
- ordered_blocks,
- original_type_by_index,
- position_by_index,
- ):
+ child_block: Block,
+ main_blocks: list[Block],
+ ordered_blocks: list[Block],
+ original_type_by_index: dict[int, str],
+ position_by_index: dict[int, int],
+ ) -> Block | None:
child_type = original_type_by_index[child_block["index"]]
if child_type not in self.VISUAL_CHILD_TYPES:
return None
@@ -466,46 +474,46 @@ class MagicModel:
)
@staticmethod
- def __child_kind(block_type):
+ def __child_kind(block_type: str) -> str:
if block_type == BlockType.CAPTION:
return "caption"
return "footnote"
@staticmethod
- def __make_child_block(block, block_type):
+ def __make_child_block(block: Block, block_type: str) -> Block:
return MagicModel.__copy_block_fields(block, type=block_type)
- def __sync_layout_det_type(self, block_index, block_type):
+ def __sync_layout_det_type(self, block_index: int, block_type: str) -> None:
layout_det = self.__layout_det_by_index.get(block_index)
if layout_det is not None:
layout_det["type"] = block_type
- def get_page_blocks(self):
+ def get_page_blocks(self) -> list[Block]:
return self.page_blocks
- def get_all_image_spans(self):
+ def get_all_image_spans(self) -> list[Span]:
return self.all_image_spans
- def get_preproc_blocks(self):
+ def get_preproc_blocks(self) -> list[Block]:
return self.preproc_blocks
- def get_discarded_blocks(self):
+ def get_discarded_blocks(self) -> list[Block]:
return self.discarded_blocks
- def get_imgs(self):
+ def get_imgs(self) -> list[dict[str, Any]]:
return self.image_groups
- def get_tables(self):
+ def get_tables(self) -> list[dict[str, Any]]:
return self.table_groups
- def get_charts(self):
+ def get_charts(self) -> list[dict[str, Any]]:
return self.chart_groups
- def get_image_blocks(self):
- return [block for block in self.page_blocks if block["type"] == BlockType.IMAGE]
+ def get_image_blocks(self) -> list[Block]:
+ return [block for block in self.page_blocks if block.type == BlockType.IMAGE]
- def get_table_blocks(self):
- return [block for block in self.page_blocks if block["type"] == BlockType.TABLE]
+ def get_table_blocks(self) -> list[Block]:
+ return [block for block in self.page_blocks if block.type == BlockType.TABLE]
- def get_chart_blocks(self):
- return [block for block in self.page_blocks if block["type"] == BlockType.CHART]
+ def get_chart_blocks(self) -> list[Block]:
+ return [block for block in self.page_blocks if block.type == BlockType.CHART]
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index e59e3e17..4380587b 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -1,43 +1,35 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import re
from html import unescape
+from typing import Any
from loguru import logger
-from mineru.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
-from mineru.utils.config_reader import get_latex_delimiter_config
-from mineru.backend.pipeline.para_split import ListLineTag
-from mineru.utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode
-from mineru.utils.language import detect_lang
-from mineru.backend.utils.markdown_utils import (
- escape_conservative_markdown_text,
- escape_text_block_markdown_prefix,
-)
-
-
-def make_blocks_to_markdown(paras_of_layout,
- mode,
- img_buket_path='',
- ):
+from ...types import Block, Line, Span
+from ...utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
+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:
page_markdown = []
for para_block in paras_of_layout:
- para_text = ''
- para_type = para_block['type']
- if para_type in [
- BlockType.TEXT,
- BlockType.LIST,
- BlockType.INDEX,
- BlockType.ABSTRACT,
- BlockType.REF_TEXT
- ]:
+ para_text = ""
+ 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)}'
+ 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']})"
@@ -59,7 +51,7 @@ def make_blocks_to_markdown(paras_of_layout,
elif para_type == BlockType.CODE:
para_text = merge_visual_blocks_to_markdown(para_block)
- if para_text.strip() == '':
+ if para_text.strip() == "":
continue
else:
page_markdown.append(para_text.strip())
@@ -67,17 +59,17 @@ def make_blocks_to_markdown(paras_of_layout,
return page_markdown
-def merge_visual_blocks_to_markdown(para_block, img_buket_path=''):
+def merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = "") -> str:
# 将 image/table/chart/code 这类视觉块的子 block 按阅读顺序拼接成 markdown。
# 这里不再写死 caption/body/footnote 的优先级,而是先展开成 segment,
# 再根据 markdown_line / html_block 两类片段决定分隔方式。
rendered_segments = []
- for block in get_blocks_in_index_order(para_block.get('blocks', [])):
+ for block in get_blocks_in_index_order(para_block.blocks):
render_block = _inherit_parent_code_render_metadata(block, para_block)
rendered_segments.extend(render_visual_block_segments(render_block, img_buket_path, para_block))
- para_text = ''
+ para_text = ""
prev_segment_kind = None
for segment_text, segment_kind in rendered_segments:
if para_text:
@@ -88,44 +80,44 @@ def merge_visual_blocks_to_markdown(para_block, img_buket_path=''):
return para_text
-def get_blocks_in_index_order(blocks):
+def get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:
# 按 middle json 中的 index 排序子 block;
# 如果 index 缺失,则退化为保持原始顺序。
return [
block
for _, block in sorted(
enumerate(blocks),
- key=lambda item: (item[1].get('index', float('inf')), item[0]),
+ key=lambda item: (item[1].get("index", float("inf")), item[0]),
)
]
-def _inherit_parent_code_render_metadata(block, parent_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.get("type") != BlockType.CODE_BODY:
return block
- if parent_block.get('type') != BlockType.CODE:
+ if parent_block.get("type") != BlockType.CODE:
return block
- needs_sub_type = 'sub_type' not in block and 'sub_type' in parent_block
- needs_guess_lang = 'guess_lang' not in block and 'guess_lang' in parent_block
+ needs_sub_type = "sub_type" not in block and "sub_type" in parent_block
+ needs_guess_lang = "guess_lang" not in block and "guess_lang" in parent_block
if not needs_sub_type and not needs_guess_lang:
return block
render_block = dict(block)
if needs_sub_type:
- render_block['sub_type'] = parent_block['sub_type']
+ render_block["sub_type"] = parent_block["sub_type"]
if needs_guess_lang:
- render_block['guess_lang'] = parent_block['guess_lang']
+ render_block["guess_lang"] = parent_block["guess_lang"]
return render_block
-def render_visual_block_segments(block, img_buket_path='', para_block=None):
+def render_visual_block_segments(block: Block, img_buket_path: str = "", para_block: Block | None = None) -> list[str]:
# 将单个视觉子 block 渲染成一个或多个 segment。
# 文本类子块统一输出 markdown_line;
# table 的 html 输出为 html_block,供后续决定是否需要空行隔开。
- block_type = block['type']
+ block_type = block["type"]
if block_type in [
BlockType.IMAGE_CAPTION,
@@ -140,88 +132,89 @@ def render_visual_block_segments(block, img_buket_path='', para_block=None):
]:
block_text = merge_para_with_text(block)
if block_text.strip():
- return [(block_text, 'markdown_line')]
+ return [(block_text, "markdown_line")]
return []
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((
- f"![]({img_buket_path}/{span['image_path']})",
- 'markdown_line',
- ))
+ if span.get("image_path", ""):
+ rendered_segments.append(
+ (
+ f"![]({img_buket_path}/{span['image_path']})",
+ "markdown_line",
+ )
+ )
details_block = _build_visual_details_block(
- span.get('content', ''),
- (para_block or {}).get('sub_type') or 'image content',
+ span.get("content", ""),
+ (para_block or {}).get("sub_type") or "image content",
)
if details_block:
- rendered_segments.append((details_block, 'details_block'))
+ rendered_segments.append((details_block, "details_block"))
return rendered_segments
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', '')
+ (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", "")
]
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),
- 'html_block',
- ))
- elif span.get('image_path', ''):
- rendered_segments.append((f"![]({img_buket_path}/{span['image_path']})", 'markdown_line'))
+ if span.get("html", ""):
+ rendered_segments.append(
+ (
+ _format_embedded_html(span["html"], img_buket_path),
+ "html_block",
+ )
+ )
+ elif span.get("image_path", ""):
+ rendered_segments.append((f"![]({img_buket_path}/{span['image_path']})", "markdown_line"))
return rendered_segments
return []
-def get_visual_block_separator(prev_segment_kind, current_segment_kind):
+def get_visual_block_separator(prev_segment_kind: str, current_segment_kind: str) -> str:
# 根据前后 segment 类型决定分隔符:
# 1. 普通 markdown 行之间用 hard break(" \\n")
# 2. 进入 html block 前只换一行
# 3. html block 后必须留空行,否则后续文本仍会被当作 html 块内容
- if prev_segment_kind == 'html_block':
+ if prev_segment_kind == "html_block":
# Raw HTML blocks need a blank line after them, otherwise the following
# markdown text is still treated as part of the HTML block.
- return '\n\n'
- if prev_segment_kind == 'details_block' or current_segment_kind == 'details_block':
- return '\n\n'
- if current_segment_kind == 'html_block':
- return '\n'
- return ' \n'
+ return "\n\n"
+ if prev_segment_kind == "details_block" or current_segment_kind == "details_block":
+ return "\n\n"
+ if current_segment_kind == "html_block":
+ return "\n"
+ return " \n"
latex_delimiters_config = get_latex_delimiter_config()
-default_delimiters = {
- 'display': {'left': '$$', 'right': '$$'},
- 'inline': {'left': '$', 'right': '$'}
-}
+default_delimiters = {"display": {"left": "$$", "right": "$$"}, "inline": {"left": "$", "right": "$"}}
delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
-display_left_delimiter = delimiters['display']['left']
-display_right_delimiter = delimiters['display']['right']
-inline_left_delimiter = delimiters['inline']['left']
-inline_right_delimiter = delimiters['inline']['right']
+display_left_delimiter = delimiters["display"]["left"]
+display_right_delimiter = delimiters["display"]["right"]
+inline_left_delimiter = delimiters["inline"]["left"]
+inline_right_delimiter = delimiters["inline"]["right"]
-CJK_LANGS = {'zh', 'ja', 'ko'}
+CJK_LANGS = {"zh", "ja", "ko"}
-def _prefix_table_img_src(html, img_buket_path):
+def _prefix_table_img_src(html: str, img_buket_path: str) -> str:
"""Prefix non-data image sources in table HTML with img_buket_path."""
if not html or not img_buket_path:
return html
@@ -233,76 +226,69 @@ def _prefix_table_img_src(html, img_buket_path):
)
-def _replace_eq_tags_in_table_html(html):
+def _replace_eq_tags_in_table_html(html: str) -> str:
"""Replace <eq>...</eq> tags in table HTML with inline math delimiters."""
if not html:
return html
return re.sub(
- r'<eq>(.*?)</eq>',
- lambda match: (
- f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} "
- ),
+ r"<eq>(.*?)</eq>",
+ lambda match: f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} ",
html,
flags=re.DOTALL,
)
-def _format_embedded_html(html, img_buket_path):
+def _format_embedded_html(html: str, img_buket_path: str) -> str:
"""Normalize embedded table HTML for markdown/content outputs."""
return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))
-def _normalize_visual_content(content):
+def _normalize_visual_content(content: str) -> str:
"""将视觉块识别内容统一成字符串,便于 markdown 和结构化输出复用。"""
if isinstance(content, list):
return "\n".join(str(item) for item in content if str(item).strip())
if isinstance(content, str):
return content.strip()
- return ''
+ return ""
-def _build_visual_details_block(content, summary):
+def _build_visual_details_block(content: str, summary: str) -> str:
"""根据视觉块的识别文本生成 VLM 风格的折叠详情块。"""
normalized_content = _normalize_visual_content(content)
if not normalized_content:
- return ''
+ return ""
- return (
- "<details>\n"
- f"<summary>{summary}</summary>\n\n"
- f"{normalized_content}\n"
- "</details>"
- )
+ return f"<details>\n<summary>{summary}</summary>\n\n{normalized_content}\n</details>"
-def _apply_visual_sub_type(para_content, para_block):
+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.get("sub_type")
if sub_type:
- para_content['sub_type'] = sub_type
+ para_content["sub_type"] = sub_type
-def merge_para_with_text(para_block):
+def merge_para_with_text(para_block: Block) -> str:
if _is_fenced_code_block(para_block):
code_text = _merge_para_text(
para_block,
escape_markdown=False,
- list_line_break='\n',
+ list_line_break="\n",
)
if not code_text:
- return ''
- code_text = '\n'.join(line.rstrip() for line in code_text.split('\n'))
- guess_lang = para_block.get('guess_lang', 'txt') or 'txt'
+ return ""
+ code_text = "\n".join(line.rstrip() for line in code_text.split("\n"))
+ guess_lang = para_block.get("guess_lang", "txt") or "txt"
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.get("type") == BlockType.TEXT:
para_text = escape_text_block_markdown_prefix(para_text)
return para_text
-def _merge_para_text(para_block, escape_markdown=True, list_line_break=' \n'):
+def _merge_para_text(para_block: Block, escape_markdown: bool = True, list_line_break: str = " \n") -> str:
# 将普通文本段落 block 渲染成 markdown 字符串。
# 处理流程分为三层:
# 1. 先收集文本内容做语言检测
@@ -311,12 +297,12 @@ def _merge_para_text(para_block, escape_markdown=True, list_line_break=' \n'):
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
@@ -335,48 +321,45 @@ def _merge_para_text(para_block, escape_markdown=True, list_line_break=' \n'):
if suffix:
para_parts.append(suffix)
- return ''.join(para_parts).rstrip()
+ return "".join(para_parts).rstrip()
-def _is_fenced_code_block(para_block):
- return (
- para_block.get('type') == BlockType.CODE_BODY
- and para_block.get('sub_type') == BlockType.CODE
- )
+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
-def _collect_text_for_lang_detection(para_block):
+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:
- block_text_parts.append(_normalize_text_content(span.get('content', '')))
- return ''.join(block_text_parts)
+ 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)
-def _normalize_text_content(content):
+def _normalize_text_content(content: str) -> str:
# 对原始文本做统一归一化,当前只负责全角转半角。
# 单独拆出来是为了让语言检测和渲染阶段复用同一套文本预处理。
- return full_to_half_exclude_marks(content or '')
+ return full_to_half_exclude_marks(content or "")
-def _render_span(span, escape_markdown=True):
+def _render_span(span: Span, escape_markdown: bool = True) -> str:
# 将单个 span 渲染成 markdown 片段。
# 这里只负责“渲染成什么文本”,不决定后面是否补空格。
- span_type = span['type']
- content = ''
+ span_type = span["type"]
+ content = ""
if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.get('content', ''))
+ content = _normalize_text_content(span.get("content", ""))
if escape_markdown:
content = escape_special_markdown_char(content)
elif span_type == ContentType.INLINE_EQUATION:
- if span.get('content', ''):
+ if span.get("content", ""):
content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
elif span_type == ContentType.INTERLINE_EQUATION:
- if span.get('content', ''):
+ if span.get("content", ""):
content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
else:
return None
@@ -388,83 +371,83 @@ def _render_span(span, escape_markdown=True):
return span_type, content
-def _join_rendered_span(para_block, block_lang, line, line_idx, span_idx, span_type, content):
+def _join_rendered_span(
+ para_block: Block, block_lang: str, line: Line, line_idx: int, span_idx: int, span_type: str, content: str
+) -> str:
# 根据语言和上下文决定当前 span 后面的分隔符。
# 这里集中处理:
# 1. CJK 与西文的空格差异
# 2. 西文行尾连字符是否需要跨行合并
# 3. 独立公式是否作为块内容直接插入
if span_type == ContentType.INTERLINE_EQUATION:
- return content, ''
+ 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:
- return content, ''
- return content, ' '
+ return content, ""
+ return content, " "
if span_type not in [ContentType.TEXT, ContentType.INLINE_EQUATION]:
- return content, ''
+ return content, ""
- if (
- is_last_span
- and span_type == ContentType.TEXT
- and is_hyphen_at_line_end(content)
- ):
+ if is_last_span and span_type == ContentType.TEXT and is_hyphen_at_line_end(content):
if _next_line_starts_with_lowercase_text(para_block, line_idx):
- return content[:-1], ''
- return content, ''
+ return content[:-1], ""
+ return content, ""
- return content, ' '
+ return content, " "
-def _line_prefix(line_idx, line, list_line_break=' \n'):
+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):
return list_line_break
- return ''
+ return ""
-def _next_line_starts_with_lowercase_text(para_block, line_idx):
+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].get("spans")
if not next_line_spans:
return False
next_span = next_line_spans[0]
- if next_span.get('type') != ContentType.TEXT:
+ if next_span.get("type") != ContentType.TEXT:
return False
- next_content = _normalize_text_content(next_span.get('content', ''))
+ next_content = _normalize_text_content(next_span.get("content", ""))
return bool(next_content) and next_content[0].islower()
-def merge_adjacent_ref_text_blocks_for_content(para_blocks):
+def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:
merged_blocks = []
ref_group = []
- def flush_ref_group():
+ def flush_ref_group() -> None:
nonlocal ref_group
if not ref_group:
return
if len(ref_group) == 1:
merged_blocks.append(ref_group[0])
else:
- merged_blocks.append({
- 'type': BlockType.REF_TEXT,
- 'blocks': list(ref_group),
- 'bbox': ref_group[0].get('bbox'),
- })
+ merged_blocks.append(
+ {
+ "type": BlockType.REF_TEXT,
+ "blocks": list(ref_group),
+ "bbox": ref_group[0].get("bbox"),
+ }
+ )
ref_group = []
for para_block in para_blocks or []:
- if para_block.get('type') == BlockType.REF_TEXT:
+ if para_block.get("type") == BlockType.REF_TEXT:
ref_group.append(para_block)
continue
@@ -475,7 +458,7 @@ def merge_adjacent_ref_text_blocks_for_content(para_blocks):
return merged_blocks
-def _build_bbox(para_bbox, page_size):
+def _build_bbox(para_bbox: list[float], page_size: list[int]) -> tuple[int, int, int, int]:
if not para_bbox or not page_size:
return None
@@ -489,84 +472,84 @@ def _build_bbox(para_bbox, page_size):
]
-def _get_ref_text_item_blocks(para_block):
- return para_block.get('blocks') or [para_block]
+def _get_ref_text_item_blocks(para_block: Block) -> list[Block]:
+ return para_block.get("blocks") or [para_block]
-def _split_list_item_blocks(para_block):
+def _split_list_item_blocks(para_block: Block) -> list[Block]:
item_blocks = []
current_lines = []
- for line_idx, line in enumerate(para_block.get('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:
- item_blocks.append({
- 'type': BlockType.TEXT,
- 'lines': current_lines,
- })
+ item_blocks.append(
+ {
+ "type": BlockType.TEXT,
+ "lines": current_lines,
+ }
+ )
current_lines = []
current_lines.append(line)
if current_lines:
- item_blocks.append({
- 'type': BlockType.TEXT,
- 'lines': current_lines,
- })
+ item_blocks.append(
+ {
+ "type": BlockType.TEXT,
+ "lines": current_lines,
+ }
+ )
return item_blocks
-def _get_body_data(para_block):
- def get_data_from_spans(lines):
+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.get('spans', []):
- span_type = span.get('type')
+ for span in line.spans:
+ span_type = span.get("type")
if span_type == ContentType.TABLE:
- return span.get('image_path', ''), span.get('html', '')
+ return span.get("image_path", ""), span.get("html", "")
if span_type == ContentType.CHART:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
if span_type == ContentType.IMAGE:
- return span.get('image_path', ''), _normalize_visual_content(span.get('content', ''))
+ return span.get("image_path", ""), _normalize_visual_content(span.get("content", ""))
if span_type == ContentType.INTERLINE_EQUATION:
- return span.get('image_path', ''), span.get('content', '')
- return '', ''
+ return span.get("image_path", ""), span.get("content", "")
+ return "", ""
- if 'blocks' in para_block:
- for block in para_block['blocks']:
- block_type = block.get('type')
+ if "blocks" in para_block:
+ for block in para_block["blocks"]:
+ block_type = block.get("type")
if block_type in [
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
BlockType.CHART_BODY,
BlockType.CODE_BODY,
]:
- result = get_data_from_spans(block.get('lines', []))
- if result != ('', '') or block_type == BlockType.CHART_BODY:
+ result = get_data_from_spans(block.lines)
+ if result != ("", "") or block_type == BlockType.CHART_BODY:
return result
- return '', ''
+ return "", ""
- return get_data_from_spans(para_block.get('lines', []))
+ return get_data_from_spans(para_block.lines)
-def merge_para_with_text_v2(para_block):
+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.get("type")
- for line_idx, line in enumerate(para_block.get('lines', [])):
- for span_idx, span in enumerate(line.get('spans', [])):
- span_type = span.get('type')
+ for line_idx, line in enumerate(para_block.lines):
+ for span_idx, span in enumerate(line.spans):
+ span_type = span.get("type")
if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.get('content', ''))
+ content = _normalize_text_content(span.get("content", ""))
if not content.strip():
continue
- output_type = (
- ContentTypeV2.SPAN_PHONETIC
- if para_type == BlockType.PHONETIC
- else ContentTypeV2.SPAN_TEXT
- )
- is_last_span = span_idx == len(line['spans']) - 1
+ output_type = ContentTypeV2.SPAN_PHONETIC if para_type == BlockType.PHONETIC else ContentTypeV2.SPAN_TEXT
+ 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} "
@@ -582,32 +565,38 @@ def merge_para_with_text_v2(para_block):
else:
rendered_content = f"{content} "
- if para_content and para_content[-1]['type'] == output_type:
- para_content[-1]['content'] += rendered_content
+ if para_content and para_content[-1]["type"] == output_type:
+ para_content[-1]["content"] += rendered_content
else:
- para_content.append({
- 'type': output_type,
- 'content': rendered_content,
- })
+ para_content.append(
+ {
+ "type": output_type,
+ "content": rendered_content,
+ }
+ )
elif span_type == ContentType.INLINE_EQUATION:
- content = span.get('content', '').strip()
+ content = span.get("content", "").strip()
if content:
- para_content.append({
- 'type': ContentTypeV2.SPAN_EQUATION_INLINE,
- 'content': content,
- })
-
- if para_content and para_content[-1]['type'] in [
+ para_content.append(
+ {
+ "type": ContentTypeV2.SPAN_EQUATION_INLINE,
+ "content": content,
+ }
+ )
+
+ if para_content and para_content[-1]["type"] in [
ContentTypeV2.SPAN_TEXT,
ContentTypeV2.SPAN_PHONETIC,
]:
- para_content[-1]['content'] = para_content[-1]['content'].rstrip()
+ para_content[-1]["content"] = para_content[-1]["content"].rstrip()
return para_content
-def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):
- para_type = para_block['type']
+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_content = None
if para_type in [
BlockType.TEXT,
@@ -616,8 +605,8 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
BlockType.ABSTRACT,
]:
para_content = {
- 'type': ContentType.TEXT,
- 'text': merge_para_with_text(para_block),
+ "type": ContentType.TEXT,
+ "text": merge_para_with_text(para_block),
}
elif para_type in [
BlockType.HEADER,
@@ -627,123 +616,123 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
BlockType.PAGE_FOOTNOTE,
]:
para_content = {
- 'type': para_type,
- 'text': merge_para_with_text(para_block),
+ "type": para_type,
+ "text": merge_para_with_text(para_block),
}
elif para_type == BlockType.REF_TEXT:
para_content = {
- 'type': BlockType.LIST,
- 'sub_type': BlockType.REF_TEXT,
- 'list_items': [],
+ "type": BlockType.LIST,
+ "sub_type": BlockType.REF_TEXT,
+ "list_items": [],
}
for block in _get_ref_text_item_blocks(para_block):
item_text = merge_para_with_text(block)
if item_text.strip():
- para_content['list_items'].append(item_text)
+ para_content["list_items"].append(item_text)
elif para_type == BlockType.TITLE:
para_content = {
- 'type': ContentType.TEXT,
- 'text': merge_para_with_text(para_block),
+ "type": ContentType.TEXT,
+ "text": merge_para_with_text(para_block),
}
title_level = get_title_level(para_block)
if title_level != 0:
- para_content['text_level'] = title_level
+ 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', '')}",
+ "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', ''):
- para_content['text'] = merge_para_with_text(para_block)
- para_content['text_format'] = 'latex'
+ 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:
- para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
+ para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
image_path, image_content = _get_body_data(para_block)
if image_path:
- para_content['img_path'] = f"{img_buket_path}/{image_path}"
+ para_content["img_path"] = f"{img_buket_path}/{image_path}"
if image_content:
- para_content['content'] = 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 line in block['lines']:
- 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:
+ 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:
+ if span.get("image_path", ""):
+ para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ 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:
- if span.get('html', ''):
+ 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:
+ if span.get("html", ""):
para_content[BlockType.TABLE_BODY] = _format_embedded_html(
- span['html'],
+ span["html"],
img_buket_path,
)
- if span.get('image_path', ''):
- para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
+ 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 = {
- 'type': ContentType.CHART,
- 'img_path': '',
- 'content': '',
+ "type": ContentType.CHART,
+ "img_path": "",
+ "content": "",
BlockType.CHART_CAPTION: [],
BlockType.CHART_FOOTNOTE: [],
}
- for block in para_block.get('blocks', []):
- 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', ''):
- para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
- if block['type'] == BlockType.CHART_CAPTION:
+ for block in para_block.blocks:
+ 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", ""):
+ para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ 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 = {
- 'type': BlockType.CODE,
- 'sub_type': para_block['sub_type'],
+ "type": BlockType.CODE,
+ "sub_type": para_block["sub_type"],
BlockType.CODE_CAPTION: [],
BlockType.CODE_FOOTNOTE: [],
}
- for block in para_block.get('blocks', []):
+ 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:
return None
- bbox = _build_bbox(para_block.get('bbox'), page_size)
+ bbox = _build_bbox(para_block.get("bbox"), page_size)
if bbox:
- para_content['bbox'] = bbox
- para_content['page_idx'] = page_idx
+ para_content["bbox"] = bbox
+ para_content["page_idx"] = page_idx
return para_content
-def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
- para_type = para_block['type']
+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_content = None
if para_type in [
@@ -766,8 +755,8 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
else:
raise ValueError(f"Unknown para_type: {para_type}")
para_content = {
- 'type': content_type,
- 'content': {
+ "type": content_type,
+ "content": {
f"{content_type}_content": merge_para_with_text_v2(para_block),
},
}
@@ -775,17 +764,17 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
title_level = get_title_level(para_block)
if title_level != 0:
para_content = {
- 'type': ContentTypeV2.TITLE,
- 'content': {
- 'title_content': merge_para_with_text_v2(para_block),
- 'level': title_level,
+ "type": ContentTypeV2.TITLE,
+ "content": {
+ "title_content": merge_para_with_text_v2(para_block),
+ "level": title_level,
},
}
else:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
- 'paragraph_content': merge_para_with_text_v2(para_block),
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
+ "paragraph_content": merge_para_with_text_v2(para_block),
},
}
elif para_type in [
@@ -793,115 +782,115 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
BlockType.ABSTRACT,
]:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
- 'paragraph_content': merge_para_with_text_v2(para_block),
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
+ "paragraph_content": merge_para_with_text_v2(para_block),
},
}
elif para_type == BlockType.INTERLINE_EQUATION:
image_path, math_content = _get_body_data(para_block)
para_content = {
- 'type': ContentTypeV2.EQUATION_INTERLINE,
- 'content': {
- 'math_content': math_content,
- 'math_type': 'latex',
- 'image_source': {'path': f"{img_buket_path}/{image_path}"},
+ "type": ContentTypeV2.EQUATION_INTERLINE,
+ "content": {
+ "math_content": math_content,
+ "math_type": "latex",
+ "image_source": {"path": f"{img_buket_path}/{image_path}"},
},
}
elif para_type == BlockType.IMAGE:
image_caption = []
image_footnote = []
image_path, image_content = _get_body_data(para_block)
- for block in para_block.get('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,
- 'content': {
- 'image_source': {'path': f"{img_buket_path}/{image_path}"},
- 'image_caption': image_caption,
- 'image_footnote': image_footnote,
+ "type": ContentTypeV2.IMAGE,
+ "content": {
+ "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_caption": image_caption,
+ "image_footnote": image_footnote,
},
}
- if image_content or para_block.get('sub_type'):
- para_content['content']['content'] = image_content
+ if image_content or para_block.get("sub_type"):
+ para_content["content"]["content"] = image_content
_apply_visual_sub_type(para_content, para_block)
elif para_type == BlockType.TABLE:
table_caption = []
table_footnote = []
image_path, html = _get_body_data(para_block)
table_html = _format_embedded_html(html, img_buket_path)
- table_nest_level = 2 if table_html.count('<table') > 1 else 1
- if 'colspan' in table_html or 'rowspan' in table_html or table_nest_level > 1:
+ table_nest_level = 2 if table_html.count("<table") > 1 else 1
+ if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
table_type = ContentTypeV2.TABLE_COMPLEX
else:
table_type = ContentTypeV2.TABLE_SIMPLE
- for block in para_block.get('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,
- 'content': {
- 'image_source': {'path': f"{img_buket_path}/{image_path}"},
- 'table_caption': table_caption,
- 'table_footnote': table_footnote,
- 'html': table_html,
- 'table_type': table_type,
- 'table_nest_level': table_nest_level,
+ "type": ContentTypeV2.TABLE,
+ "content": {
+ "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "table_caption": table_caption,
+ "table_footnote": table_footnote,
+ "html": table_html,
+ "table_type": table_type,
+ "table_nest_level": table_nest_level,
},
}
elif para_type == BlockType.CHART:
chart_caption = []
chart_footnote = []
image_path, _ = _get_body_data(para_block)
- for block in para_block.get('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,
- 'content': {
- 'image_source': {'path': f"{img_buket_path}/{image_path}"},
- 'content': '',
- 'chart_caption': chart_caption,
- 'chart_footnote': chart_footnote,
+ "type": ContentTypeV2.CHART,
+ "content": {
+ "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "content": "",
+ "chart_caption": chart_caption,
+ "chart_footnote": chart_footnote,
},
}
elif para_type == BlockType.CODE:
code_caption = []
code_footnote = []
code_content = []
- for block in para_block.get('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_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']
+ 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_footnote': code_footnote,
- 'code_language': para_block.get('guess_lang', 'txt'),
+ "type": ContentTypeV2.CODE,
+ "content": {
+ "code_caption": code_caption,
+ "code_content": code_content,
+ "code_footnote": code_footnote,
+ "code_language": para_block.get("guess_lang", "txt"),
},
}
elif sub_type == BlockType.ALGORITHM:
para_content = {
- 'type': ContentTypeV2.ALGORITHM,
- 'content': {
- 'algorithm_caption': code_caption,
- 'algorithm_content': code_content,
- 'algorithm_footnote': code_footnote,
+ "type": ContentTypeV2.ALGORITHM,
+ "content": {
+ "algorithm_caption": code_caption,
+ "algorithm_content": code_content,
+ "algorithm_footnote": code_footnote,
},
}
else:
@@ -911,15 +900,17 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
for block in _get_ref_text_item_blocks(para_block):
item_content = merge_para_with_text_v2(block)
if item_content:
- list_items.append({
- 'item_type': 'text',
- 'item_content': item_content,
- })
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
para_content = {
- 'type': ContentTypeV2.LIST,
- 'content': {
- 'list_type': ContentTypeV2.LIST_REF,
- 'list_items': list_items,
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": ContentTypeV2.LIST_REF,
+ "list_items": list_items,
},
}
elif para_type == BlockType.LIST:
@@ -927,16 +918,18 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
for block in _split_list_item_blocks(para_block):
item_content = merge_para_with_text_v2(block)
if item_content:
- list_items.append({
- 'item_type': 'text',
- 'item_content': item_content,
- })
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
para_content = {
- 'type': ContentTypeV2.LIST,
- 'content': {
- 'list_type': ContentTypeV2.LIST_TEXT,
- 'attribute': para_block.get('attribute', 'unordered'),
- 'list_items': list_items,
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": ContentTypeV2.LIST_TEXT,
+ "attribute": para_block.get("attribute", "unordered"),
+ "list_items": list_items,
},
}
elif para_type == BlockType.INDEX:
@@ -944,46 +937,47 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
for block in _split_list_item_blocks(para_block):
item_content = merge_para_with_text_v2(block)
if item_content:
- list_items.append({
- 'item_type': 'text',
- 'item_content': item_content,
- })
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
para_content = {
- 'type': ContentTypeV2.INDEX,
- 'content': {
- 'list_type': ContentTypeV2.LIST_TEXT,
- 'list_items': list_items,
+ "type": ContentTypeV2.INDEX,
+ "content": {
+ "list_type": ContentTypeV2.LIST_TEXT,
+ "list_items": list_items,
},
}
if not para_content:
return None
- bbox = _build_bbox(para_block.get('bbox'), page_size)
+ bbox = _build_bbox(para_block.get("bbox"), page_size)
if bbox:
- para_content['bbox'] = bbox
+ para_content["bbox"] = bbox
return para_content
-def union_make(pdf_info_dict: list,
- make_mode: str,
- img_buket_path: str = '',
- ):
+def union_make(
+ pdf_info_dict: list[dict[str, Any]],
+ make_mode: str,
+ img_buket_path: str = "",
+) -> str:
output_content = []
for page_info in pdf_info_dict:
- paras_of_layout = page_info.get('para_blocks')
- paras_of_discarded = page_info.get('discarded_blocks')
- page_idx = page_info.get('page_idx')
- page_size = page_info.get('page_size')
+ paras_of_layout = page_info.get("para_blocks")
+ paras_of_discarded = page_info.get("discarded_blocks")
+ page_idx = page_info.get("page_idx")
+ page_size = page_info.get("page_size")
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
if not paras_of_layout:
continue
page_markdown = make_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path)
output_content.extend(page_markdown)
elif make_mode == MakeMode.CONTENT_LIST:
- para_blocks = merge_adjacent_ref_text_blocks_for_content(
- (paras_of_layout or []) + (paras_of_discarded or [])
- )
+ para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))
if not para_blocks:
continue
for para_block in para_blocks:
@@ -991,9 +985,7 @@ def union_make(pdf_info_dict: list,
if para_content:
output_content.append(para_content)
elif make_mode == MakeMode.CONTENT_LIST_V2:
- para_blocks = merge_adjacent_ref_text_blocks_for_content(
- (paras_of_layout or []) + (paras_of_discarded or [])
- )
+ para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))
page_contents = []
if para_blocks:
for para_block in para_blocks:
@@ -1003,7 +995,7 @@ def union_make(pdf_info_dict: list,
output_content.append(page_contents)
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
- return '\n\n'.join(output_content)
+ return "\n\n".join(output_content)
elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:
return output_content
else:
@@ -1011,14 +1003,14 @@ def union_make(pdf_info_dict: list,
return None
-def get_title_level(block):
- title_level = block.get('level', 1)
+def get_title_level(block: Block) -> int:
+ title_level = block.get("level", 1)
if title_level < 1:
title_level = 0
return title_level
-def escape_special_markdown_char(content):
+def escape_special_markdown_char(content: str) -> str:
"""
转义正文里对markdown语法有特殊意义的字符
"""
diff --git a/mineru/backend/utils/html_image_utils.py b/mineru/backend/utils/html_image_utils.py
index 777c909e..973be9a7 100644
--- a/mineru/backend/utils/html_image_utils.py
+++ b/mineru/backend/utils/html_image_utils.py
@@ -1,13 +1,16 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import base64
import re
from loguru import logger
-from mineru.backend.utils.office_image import is_vector_image_part, serialize_office_image
-from mineru.utils.enum_class import BlockType, ContentType
-from mineru.utils.hash_utils import str_sha256
-
+from ...data.data_reader_writer import DataWriter
+from ...types import Block, Span
+from ...utils.enum_class import BlockType, ContentType
+from ...utils.hash_utils import str_sha256
+from .office_image import is_vector_image_part, serialize_office_image
INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,(.+)", re.DOTALL)
@@ -19,10 +22,10 @@ def _normalize_image_extension(fmt: str) -> str:
def _save_inline_vector_image(
img_bytes: bytes,
- image_writer,
+ image_writer: DataWriter,
fmt: str,
page_index: int,
-):
+) -> str | None:
"""将 HTML 表格内联的 WMF/EMF 矢量图转换为可渲染占位图后落盘。"""
content_type = f"image/{fmt.lower()}"
rendered_data_uri = serialize_office_image(
@@ -35,9 +38,7 @@ def _save_inline_vector_image(
rendered_match = INLINE_IMAGE_DATA_URI_RE.match(rendered_data_uri)
if not rendered_match:
- logger.warning(
- f"Unrecognized converted vector image format in page {page_index}, skipping."
- )
+ logger.warning(f"Unrecognized converted vector image format in page {page_index}, skipping.")
return None
rendered_fmt = _normalize_image_extension(rendered_match.group(1))
@@ -52,7 +53,7 @@ def _save_inline_vector_image(
return img_path
-def _write_image_once(image_writer, img_path: str, img_bytes: bytes) -> None:
+def _write_image_once(image_writer: DataWriter, img_path: str, img_bytes: bytes) -> None:
"""同一 writer 生命周期内同一路径只写一次,便于复用标准占位图。"""
written_paths = getattr(image_writer, "_mineru_written_image_paths", None)
if written_paths is None:
@@ -70,7 +71,7 @@ def _write_image_once(image_writer, img_path: str, img_bytes: bytes) -> None:
written_paths.add(img_path)
-def save_base64_image(b64_data_uri: str, image_writer, page_index: int):
+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
@@ -101,12 +102,12 @@ def save_base64_image(b64_data_uri: str, image_writer, page_index: int):
return img_path
-def replace_inline_base64_img_src(markup: str, image_writer, 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, _writer=image_writer, _idx=page_index):
+ 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)
if img_path:
return f'src="{img_path}"'
@@ -120,39 +121,39 @@ def replace_inline_base64_img_src(markup: str, image_writer, page_index: int) ->
def replace_inline_table_images(
- blocks: list[dict],
- image_writer,
+ blocks: list[Block],
+ image_writer: DataWriter,
page_index: int,
- table_block_type=BlockType.TABLE,
- table_body_type=BlockType.TABLE_BODY,
- table_span_type=ContentType.TABLE,
+ table_block_type: str = BlockType.TABLE,
+ table_body_type: str = BlockType.TABLE_BODY,
+ table_span_type: str = ContentType.TABLE,
) -> None:
"""Persist inline base64 images embedded inside table HTML."""
if not image_writer:
return
for block in blocks:
- if block.get("type") != table_block_type:
+ if block.type != table_block_type:
continue
- for sub_block in block.get("blocks", []):
- if sub_block.get("type") != table_body_type:
+ for sub_block in block.blocks:
+ if sub_block.type != table_body_type:
continue
- for line in sub_block.get("lines", []):
- for span in line.get("spans", []):
- if span.get("type") != table_span_type:
+ for line in sub_block.lines:
+ for span in line.spans:
+ if span.type != table_span_type:
continue
- span["html"] = replace_inline_base64_img_src(
- span.get("html", ""),
+ span.html = replace_inline_base64_img_src(
+ span.html,
image_writer,
page_index,
)
def save_span_image_if_needed(
- span: dict,
- image_writer,
+ span: Span,
+ image_writer: DataWriter,
page_index: int,
source_key: str = "image_base64",
target_key: str = "image_path",
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 122573ae..0928c9ca 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -8,24 +8,30 @@ across backends.
from __future__ import annotations
import copy
-from typing import Any, Callable
+from typing import Any, Callable, Iterator, TypeVar
from tqdm import tqdm
-from mineru.types import PageInfo
+from ...data.data_reader_writer import DataWriter
+from ...types import Block, PageInfo, Span
+from ...utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
+from ...utils.pdfium_guard import close_pdfium_child, close_pdfium_document, pdfium_guard
+from ..pipeline.model_init import run_ocr_rec_inference
+
+T = TypeVar("T")
def build_middle_json(
- model_list: list,
- images_list: list,
+ model_list: list[T],
+ images_list: list[dict[str, Any]],
pdf_doc: Any,
- image_writer: Any,
+ image_writer: DataWriter,
*,
- init_fn: Callable[..., dict],
- page_cvt_fn: Callable[..., dict],
+ init_fn: Callable[..., dict[str, Any]],
+ page_cvt_fn: Callable[[T], PageInfo],
finalize_fn: Callable[..., None],
**kwargs: Any,
-) -> dict:
+) -> dict[str, Any]:
"""Shared orchestration for the three PDF backends.
Parameters
@@ -39,12 +45,15 @@ def build_middle_json(
finalize_fn(pdf_info_list, **kwargs):
Post-processing applied once all pages are ready.
"""
- from ...utils.pdfium_guard import close_pdfium_document
middle_json = init_fn(**kwargs)
with tqdm(total=len(model_list), desc="Processing pages") as progress_bar:
append_pages(
- middle_json, model_list, images_list, pdf_doc, image_writer,
+ middle_json,
+ model_list,
+ images_list,
+ pdf_doc,
+ image_writer,
page_cvt_fn=page_cvt_fn,
progress_bar=progress_bar,
**kwargs,
@@ -56,13 +65,13 @@ def build_middle_json(
def append_pages(
- middle_json: dict,
- model_list: list,
- images_list: list,
+ middle_json: dict[str, Any],
+ model_list: list[T],
+ images_list: list[dict[str, Any]],
pdf_doc: Any,
- image_writer: Any,
+ image_writer: DataWriter | None,
*,
- page_cvt_fn: Callable[..., dict],
+ page_cvt_fn: Callable[[T, dict, Any, DataWriter | None, int], PageInfo],
page_start_index: int = 0,
progress_bar: Any = None,
**kwargs: Any,
@@ -73,7 +82,6 @@ def append_pages(
is ``page_cvt_fn``, which converts one page's model output into a
page_info dict.
"""
- from ...utils.pdfium_guard import close_pdfium_child, pdfium_guard
for offset, (page_data, image_dict) in enumerate(zip(model_list, images_list)):
page_index = page_start_index + offset
@@ -81,9 +89,7 @@ def append_pages(
try:
with pdfium_guard():
page = pdf_doc[page_index]
- page_info = page_cvt_fn(
- copy.deepcopy(page_data), image_dict, page, image_writer, page_index, **kwargs
- )
+ page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, page, image_writer, page_index, **kwargs)
if page_info is None:
with pdfium_guard():
page_w, page_h = map(int, page.get_size())
@@ -100,14 +106,12 @@ def append_pages(
progress_bar.update(1)
-def apply_post_ocr(pdf_info_list: list, ocr_model: Any) -> None:
+def apply_post_ocr(pdf_info_list: list[PageInfo], ocr_model: Any) -> None:
"""Run OCR recognition on residual ``np_img`` crops inside spans.
Common to Pipeline and Hybrid. The caller provides the OCR model object
(which has an ``ocr`` attribute pointing to the inference engine).
"""
- from mineru.backend.pipeline.model_init import run_ocr_rec_inference
- from mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
need_ocr_list = []
img_crop_list = []
@@ -138,7 +142,7 @@ def apply_post_ocr(pdf_info_list: list, ocr_model: Any) -> None:
def _iter_block_spans(block: Block) -> Iterator[Span]:
"""Depth-first generator yielding every span in a block tree."""
- for line in block.get("lines", []):
- yield from line.get("spans", [])
- for child in block.get("blocks", []):
+ for line in block.lines:
+ yield from line.spans
+ for child in block.blocks:
yield from _iter_block_spans(child)
diff --git a/mineru/backend/utils/ocr_det_utils.py b/mineru/backend/utils/ocr_det_utils.py
index e1d2aa43..175c110a 100644
--- a/mineru/backend/utils/ocr_det_utils.py
+++ b/mineru/backend/utils/ocr_det_utils.py
@@ -1,17 +1,19 @@
# Copyright (c) Opendatalab. All rights reserved.
+from typing import Any
+
import cv2
import numpy as np
from loguru import logger
-from mineru.utils.pdf_image_tools import get_crop_img
+from ...utils.pdf_image_tools import get_crop_img
OCR_DET_PADDING = 50
def get_ch_lite_ocr_det_model() -> Any:
try:
- from mineru.backend.pipeline.model_init import AtomModelSingleton
+ 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, "
@@ -20,15 +22,12 @@ def get_ch_lite_ocr_det_model() -> Any:
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'
- )
+ 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) -> list:
+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
diff --git a/mineru/backend/utils/office_chart.py b/mineru/backend/utils/office_chart.py
index ef328f43..1dd4c172 100644
--- a/mineru/backend/utils/office_chart.py
+++ b/mineru/backend/utils/office_chart.py
@@ -89,7 +89,7 @@ def html_table_from_excel_bytes(excel_bytes: bytes) -> str:
return ""
-def _extract_non_empty_worksheet_rows(worksheet) -> list[list[str]]:
+def _extract_non_empty_worksheet_rows(worksheet: object) -> list[list[str]]:
"""提取工作表中首尾有内容的行,避免空 sheet 或尾部空列撑大兜底表格。"""
raw_rows: list[list[str]] = []
for row in worksheet.iter_rows(values_only=True):
@@ -345,7 +345,7 @@ def render_chart_html_from_cache(spec: ChartSpec) -> str:
return ""
-def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook) -> str:
+def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
categories = []
for series in spec.series:
@@ -389,7 +389,7 @@ def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook) -> str:
return _render_html_table(headers, columns, row_count)
-def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook) -> str:
+def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
x_sequences, series_names, series_y_values = _read_scatter_axes_from_workbook(
spec,
workbook,
@@ -402,7 +402,7 @@ def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook) -> str:
)
-def _render_bubble_chart_from_workbook(spec: ChartSpec, workbook) -> str:
+def _render_bubble_chart_from_workbook(spec: ChartSpec, workbook: object) -> str:
x_sequences, series_names, series_y_values, series_sizes = _read_bubble_axes_from_workbook(
spec,
workbook,
@@ -457,7 +457,9 @@ def _render_bubble_chart_from_cache(spec: ChartSpec) -> str:
)
-def _read_scatter_axes_from_workbook(spec: ChartSpec, workbook):
+def _read_scatter_axes_from_workbook(
+ spec: ChartSpec, workbook: object
+) -> tuple[list[list[float]] | None, list[str], list[list[float]]]:
x_sequences = []
series_names = []
series_y_values = []
@@ -482,7 +484,9 @@ def _read_scatter_axes_from_workbook(spec: ChartSpec, workbook):
return x_sequences, series_names, series_y_values
-def _read_bubble_axes_from_workbook(spec: ChartSpec, workbook):
+def _read_bubble_axes_from_workbook(
+ spec: ChartSpec, workbook: object
+) -> tuple[list[list[float]] | None, list[str], list[list[float]], list[list[float]]]:
x_sequences = []
series_names = []
series_y_values = []
@@ -510,7 +514,7 @@ def _read_bubble_axes_from_workbook(spec: ChartSpec, workbook):
return x_sequences, series_names, series_y_values, series_sizes
-def _read_formula_vector(workbook, formula: str):
+def _read_formula_vector(workbook: object, formula: str) -> tuple[str, list[object]] | None:
parsed = _parse_formula(formula)
if parsed is None:
return None
@@ -536,7 +540,7 @@ def _read_formula_vector(workbook, formula: str):
return sheet_name, values
-def _read_formula_scalar(workbook, formula: str) -> str | None:
+def _read_formula_scalar(workbook: object, formula: str) -> str | None:
read_result = _read_formula_vector(workbook, formula)
if read_result is None:
return None
@@ -551,7 +555,7 @@ def _read_formula_scalar(workbook, formula: str) -> str | None:
return _stringify_cell_value(value)
-def _parse_formula(formula: str):
+def _parse_formula(formula: str) -> tuple[str, int, int, int, int] | None:
formula = formula.strip()
if not formula:
return None
@@ -574,7 +578,7 @@ def _unescape_formula_sheet_name(sheet_name: str) -> str:
return sheet_name.replace("''", "'")
-def _extract_reference_formula(container) -> str | None:
+def _extract_reference_formula(container: object) -> str | None:
ref_element = _find_reference_element(container)
if ref_element is None:
return None
@@ -585,7 +589,7 @@ def _extract_reference_formula(container) -> str | None:
def _extract_reference_cache(
- container,
+ container: object,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -612,7 +616,7 @@ def _extract_reference_cache(
def _extract_cache_points(
- cache_element,
+ cache_element: object,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -645,7 +649,7 @@ def _extract_cache_points(
return [points.get(index, "") for index in range(max_index + 1)]
-def _extract_multilevel_string_cache(ref_element) -> list[str]:
+def _extract_multilevel_string_cache(ref_element: object) -> list[str]:
level_maps = []
max_index = -1
for level in ref_element.findall("c:multiLvlStrCache/c:lvl", namespaces=_NS):
@@ -680,7 +684,7 @@ def _extract_multilevel_string_cache(ref_element) -> list[str]:
return rows
-def _extract_tx_formula(tx_element) -> str | None:
+def _extract_tx_formula(tx_element: object) -> str | None:
if tx_element is None:
return None
str_ref = tx_element.find("c:strRef", namespaces=_NS)
@@ -692,7 +696,7 @@ def _extract_tx_formula(tx_element) -> str | None:
return formula_element.text.strip()
-def _extract_tx_text(tx_element) -> str | None:
+def _extract_tx_text(tx_element: object) -> str | None:
if tx_element is None:
return None
@@ -708,14 +712,14 @@ def _extract_tx_text(tx_element) -> str | None:
return None
-def _extract_title_text(title_element) -> str:
+def _extract_title_text(title_element: object) -> 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):
+def _find_reference_element(container: object) -> object | None:
if container is None:
return None
for tag_name in ("strRef", "numRef", "multiLvlStrRef"):
@@ -725,14 +729,14 @@ def _find_reference_element(container):
return None
-def _first_non_none(*values):
+def _first_non_none(*values: object) -> object | None:
for value in values:
if value is not None:
return value
return None
-def _collect_plot_elements(plot_area) -> list[tuple[str, Any]]:
+def _collect_plot_elements(plot_area: object) -> list[tuple[str, object]]:
plot_elements = []
for child in plot_area:
if not isinstance(child.tag, str):
@@ -753,14 +757,14 @@ def _plot_kind_from_tag_name(tag_name: str, has_date_axis: bool) -> str:
return "category"
-def _chart_uses_date_1904(root) -> bool:
+def _chart_uses_date_1904(root: object) -> 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=None) -> str:
+def _resolve_series_name(series: SeriesSpec, index: int, workbook: object = None) -> str:
if workbook is not None and series.name_formula:
workbook_name = _read_formula_scalar(workbook, series.name_formula)
if workbook_name:
@@ -919,7 +923,7 @@ def _stringify_cache_value(
def _stringify_cell_value(
- value: Any,
+ value: object,
*,
date_hint: bool = False,
date_1904: bool = False,
@@ -963,7 +967,7 @@ def _excel_serial_to_iso(serial: float, *, date_1904: bool = False) -> str | Non
return str(excel_value)
-def _stringify_non_date_value(value: Any) -> str:
+def _stringify_non_date_value(value: object) -> 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 79e79441..342b66ea 100644
--- a/mineru/backend/utils/office_image.py
+++ b/mineru/backend/utils/office_image.py
@@ -4,12 +4,11 @@ from io import BytesIO
from pathlib import PurePosixPath
from typing import Final
-from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
from loguru import logger
+from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
-from mineru.utils.check_sys_env import is_windows_environment
-from mineru.utils.pdf_reader import image_to_b64str
-
+from ...utils.check_sys_env import is_windows_environment
+from ...utils.pdf_reader import image_to_b64str
VECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})
VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})
@@ -35,9 +34,7 @@ def is_vector_image(pil_image: Image.Image) -> bool:
return (getattr(pil_image, "format", None) or "").upper() in VECTOR_IMAGE_FORMATS
-def is_vector_image_part(
- part_name: object | None = None, content_type: str | None = None
-) -> bool:
+def is_vector_image_part(part_name: object | None = None, content_type: str | None = None) -> bool:
suffix = PurePosixPath(str(part_name or "")).suffix.lower()
if suffix in VECTOR_IMAGE_EXTENSIONS:
return True
@@ -45,9 +42,7 @@ def is_vector_image_part(
return normalized_content_type in VECTOR_IMAGE_CONTENT_TYPES
-def _vector_image_format_label(
- part_name: object | None = None, content_type: str | None = None
-) -> str:
+def _vector_image_format_label(part_name: object | None = None, content_type: str | None = None) -> str:
suffix = PurePosixPath(str(part_name or "")).suffix.lower()
normalized_content_type = (content_type or "").lower()
if suffix == ".wmf" or "wmf" in normalized_content_type:
@@ -70,9 +65,7 @@ def _load_placeholder_font(font_size: int) -> ImageFont.ImageFont:
return ImageFont.load_default()
-def create_text_placeholder(
- size: tuple[int, int], lines: list[str]
-) -> Image.Image:
+def create_text_placeholder(size: tuple[int, int], lines: list[str]) -> Image.Image:
width = max(int(size[0]), 1)
height = max(int(size[1]), 1)
placeholder = Image.new("RGB", (width, height), (240, 240, 240))
@@ -98,9 +91,7 @@ def create_text_placeholder(
for font_size in range(max(min(width, height) // 7, 10), 7, -1):
font = _load_placeholder_font(font_size)
spacing = max(2, font_size // 4)
- bbox = draw.multiline_textbbox(
- (0, 0), text, font=font, spacing=spacing, align="center"
- )
+ bbox = draw.multiline_textbbox((0, 0), text, font=font, spacing=spacing, align="center")
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
if text_width <= max_text_width and text_height <= max_text_height:
@@ -109,9 +100,7 @@ def create_text_placeholder(
text = fallback_text
font = _load_placeholder_font(max(min(width, height) // 5, 10))
spacing = 2
- bbox = draw.multiline_textbbox(
- (0, 0), text, font=font, spacing=spacing, align="center"
- )
+ bbox = draw.multiline_textbbox((0, 0), text, font=font, spacing=spacing, align="center")
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
@@ -142,25 +131,17 @@ def get_standard_vector_placeholder_data_uri() -> str:
return _standard_vector_placeholder_data_uri()
-def serialize_vector_image_with_placeholder(
- pil_image: Image.Image, image_format_override: str | None = None
-) -> str:
- image_format = (
- image_format_override or getattr(pil_image, "format", None) or "WMF/EMF"
- ).upper()
+def serialize_vector_image_with_placeholder(pil_image: Image.Image, image_format_override: str | None = None) -> str:
+ image_format = (image_format_override or getattr(pil_image, "format", None) or "WMF/EMF").upper()
if is_windows_environment():
try:
pil_image.load()
return image_to_b64str(pil_image, image_format="PNG")
except PIL_IMAGE_LOAD_ERRORS as e:
- logger.warning(
- f"Failed to render {image_format} image: {e}, size: {pil_image.size}. Using placeholder instead."
- )
+ logger.warning(f"Failed to render {image_format} image: {e}, size: {pil_image.size}. Using placeholder instead.")
else:
- logger.warning(
- f"Skipping {image_format} image on non-Windows environment, size: {pil_image.size}"
- )
+ logger.warning(f"Skipping {image_format} image on non-Windows environment, size: {pil_image.size}")
return get_standard_vector_placeholder_data_uri()
@@ -207,10 +188,7 @@ def serialize_office_image(
pil_image = Image.open(BytesIO(image_data))
pil_image.load()
except PIL_IMAGE_LOAD_ERRORS as e:
- logger.warning(
- f"Warning: image cannot be loaded by Pillow: {e}, "
- f"part_name={part_name}, content_type={content_type}"
- )
+ logger.warning(f"Warning: image cannot be loaded by Pillow: {e}, part_name={part_name}, content_type={content_type}")
return None
if is_vector_image(pil_image):
@@ -219,9 +197,7 @@ def serialize_office_image(
if pil_image.mode == "RGB":
return image_to_b64str(pil_image, image_format="JPEG")
- if pil_image.mode in {"RGBA", "LA"} or (
- pil_image.mode == "P" and "transparency" in pil_image.info
- ):
+ if pil_image.mode in {"RGBA", "LA"} or (pil_image.mode == "P" and "transparency" in pil_image.info):
return image_to_b64str(pil_image.convert("RGBA"), image_format="PNG")
return image_to_b64str(pil_image.convert("RGB"), image_format="JPEG")
diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.py
index 2408a067..a63005e7 100644
--- a/mineru/backend/utils/para_block_utils.py
+++ b/mineru/backend/utils/para_block_utils.py
@@ -1,10 +1,11 @@
# Copyright (c) Opendatalab. All rights reserved.
import copy
+from collections.abc import Generator
-from mineru.utils.enum_class import BlockType, SplitFlag
+from ...types import Block, Line, PageInfo, Span
+from ...utils.enum_class import BlockType, SplitFlag
-
-LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';')
+LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")
SECTION_MERGE_BARRIER_TYPES = {
BlockType.TITLE,
BlockType.DOC_TITLE,
@@ -29,12 +30,12 @@ INTERNAL_BLOCK_METADATA_KEYS = {
}
-def iter_block_spans(block):
- for line in block.get("lines", []):
- for span in line.get("spans", []):
+def iter_block_spans(block: Block) -> Generator[Span, None, None]:
+ for line in block.lines:
+ for span in line.spans:
yield span
- for sub_block in block.get("blocks", []):
+ for sub_block in block.blocks:
yield from iter_block_spans(sub_block)
@@ -44,7 +45,7 @@ def build_para_blocks_from_preproc(pdf_info_list: list[PageInfo]) -> None:
def merge_para_text_blocks(pdf_info_list: list[PageInfo], auto_merge_by_det: bool = False) -> None:
- ordered_blocks = []
+ 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", [])):
@@ -52,7 +53,7 @@ def merge_para_text_blocks(pdf_info_list: list[PageInfo], auto_merge_by_det: boo
for current_index in range(len(ordered_blocks) - 1, -1, -1):
current_page_idx, _, current_block = ordered_blocks[current_index]
- current_type = current_block.get("type")
+ current_type = current_block.type
if current_type == BlockType.TEXT:
if not _block_has_lines(current_block):
continue
@@ -64,7 +65,7 @@ def merge_para_text_blocks(pdf_info_list: list[PageInfo], auto_merge_by_det: boo
auto_merge_by_det,
)
elif current_type == BlockType.LIST:
- if not current_block.get("blocks"):
+ if not current_block.blocks:
continue
_merge_current_ref_text_list_block(
ordered_blocks,
@@ -74,12 +75,12 @@ def merge_para_text_blocks(pdf_info_list: list[PageInfo], auto_merge_by_det: boo
def _merge_current_text_block(
- ordered_blocks,
- current_index,
- current_page_idx,
- current_block,
- auto_merge_by_det,
-):
+ ordered_blocks: list[tuple[int, int, Block]],
+ current_index: int,
+ current_page_idx: int,
+ current_block: Block,
+ auto_merge_by_det: bool,
+) -> None:
"""处理当前 text block 的 merge_prev 候选合并和 Hybrid det 自动合并。"""
previous_block = None
if current_block.get("merge_prev"):
@@ -122,10 +123,10 @@ def _merge_current_text_block(
def _merge_current_ref_text_list_block(
- ordered_blocks,
- current_index,
- current_block,
-):
+ ordered_blocks: list[tuple[int, int, Block]],
+ current_index: int,
+ current_block: Block,
+) -> None:
"""处理当前 ref_text list 与前一个相邻 ref_text list 的合并。"""
previous_block = _find_previous_ref_text_list_block(
ordered_blocks,
@@ -145,21 +146,16 @@ def _merge_current_ref_text_list_block(
def can_auto_merge_text_blocks(
- current_block,
- previous_block,
- allow_single_line_blocks=False,
-):
+ current_block: Block,
+ previous_block: Block,
+ allow_single_line_blocks: bool = False,
+) -> bool:
"""按段落首尾文本和行几何规则判断 text 是否可合并。"""
- current_lines = current_block.get("lines", [])
- previous_lines = previous_block.get("lines", [])
+ current_lines = current_block.lines
+ previous_lines = previous_block.lines
current_metric_lines = _resolve_local_metric_lines(current_block)
previous_metric_lines = _resolve_local_metric_lines(previous_block)
- if (
- not current_lines
- or not previous_lines
- or not current_metric_lines
- or not previous_metric_lines
- ):
+ if not current_lines or not previous_lines or not current_metric_lines or not previous_metric_lines:
return False
first_metric_line = current_metric_lines[0]
@@ -193,11 +189,7 @@ def can_auto_merge_text_blocks(
if abs(current_metric_width - previous_metric_width) >= min_metric_width:
return False
- if (
- not allow_single_line_blocks
- and len(current_metric_lines) <= 1
- and len(previous_metric_lines) <= 1
- ):
+ if not allow_single_line_blocks and len(current_metric_lines) <= 1 and len(previous_metric_lines) <= 1:
return False
return _has_mergeable_block_bbox_relation(current_block, previous_block)
@@ -210,14 +202,14 @@ def cleanup_internal_para_block_metadata(pdf_info_list: list[PageInfo]) -> None:
def _find_previous_text_block(
- ordered_blocks,
- current_index,
-):
+ ordered_blocks: list[tuple[int, int, Block]],
+ current_index: int,
+) -> tuple[int, int, Block] | None:
"""查找前序 text;除 merge_prev 专用路径外默认允许跨页查找。"""
for previous_index in range(current_index - 1, -1, -1):
_, _, previous_block = ordered_blocks[previous_index]
- previous_type = previous_block.get("type")
+ previous_type = previous_block.type
if previous_type in TEXT_MERGE_BARRIER_TYPES:
return None
if previous_type != BlockType.TEXT:
@@ -230,17 +222,17 @@ def _find_previous_text_block(
def _find_previous_merge_prev_text_block(
- ordered_blocks,
- current_index,
- current_page_idx,
-):
+ ordered_blocks: list[tuple[int, int, Block]],
+ current_index: int,
+ current_page_idx: int,
+) -> tuple[int, int, Block] | None:
"""查找同页 merge_prev 提示对应的前序 text,但不跨越段落合并屏障。"""
for previous_index in range(current_index - 1, -1, -1):
previous_page_idx, _, previous_block = ordered_blocks[previous_index]
if previous_page_idx != current_page_idx:
return None
- previous_type = previous_block.get("type")
+ previous_type = previous_block.type
if previous_type in TEXT_MERGE_BARRIER_TYPES:
return None
if previous_type != BlockType.TEXT:
@@ -253,93 +245,87 @@ def _find_previous_merge_prev_text_block(
def _find_previous_ref_text_list_block(
- ordered_blocks,
- current_index,
- current_block,
-):
+ ordered_blocks: list[tuple[int, int, Block]],
+ current_index: int,
+ current_block: Block,
+) -> tuple[int, int, Block] | None:
"""查找紧邻当前 list 的前一个 ref_text list,默认允许跨页拼接。"""
previous_index = current_index - 1
if previous_index < 0:
return None
_, _, previous_block = ordered_blocks[previous_index]
- if previous_block.get("type") in SECTION_MERGE_BARRIER_TYPES:
+ if previous_block.type in SECTION_MERGE_BARRIER_TYPES:
return None
- if previous_block.get("type") != BlockType.LIST:
+ if previous_block.type != BlockType.LIST:
return None
- if not _is_ref_text_list_block(current_block) or not _is_ref_text_list_block(
- previous_block
- ):
+ if not _is_ref_text_list_block(current_block) or not _is_ref_text_list_block(previous_block):
return None
return ordered_blocks[previous_index]
def _is_ref_text_list_block(block: Block) -> bool:
"""判断 list block 是否为引用文本列表,只允许这种列表自动拼接。"""
- return block.get("type") == BlockType.LIST and block.get("sub_type") == BlockType.REF_TEXT
+ return block.type == BlockType.LIST and block.sub_type == BlockType.REF_TEXT
-def _resolve_auto_metric_lines(block: Block) -> None:
+def _resolve_auto_metric_lines(block: Block) -> list[Line]:
"""优先使用 OCR det 行提示;没有提示时退回 block 自身 lines。"""
- return block.get(OCR_DET_LINES_KEY) or block.get("lines", [])
+ return block.get(OCR_DET_LINES_KEY) or block.lines
-def _resolve_local_metric_lines(block: Block) -> None:
+def _resolve_local_metric_lines(block: Block) -> list[Line]:
"""过滤跨页追加行,避免已合并内容污染后续本地几何判定。"""
metric_lines = _resolve_auto_metric_lines(block)
- local_metric_lines = [
- line for line in metric_lines if not _is_cross_page_line(line)
- ]
+ local_metric_lines = [line for line in metric_lines if not _is_cross_page_line(line)]
return local_metric_lines or metric_lines
-def _merge_text_block(current_block, previous_block, is_cross_page):
+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.get("lines", []))
+ _mark_lines_cross_page(current_block.lines)
_mark_lines_cross_page(current_block.get(OCR_DET_LINES_KEY, []))
- previous_block.setdefault("lines", []).extend(current_block.get("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, [])
- )
+ 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
-def _mark_lines_cross_page(lines):
+def _mark_lines_cross_page(lines: list[Line]) -> None:
"""给跨页合并进来的文本行和 det hint 行同步打跨页标记。"""
for line in lines:
- for span in line.get("spans", []):
+ for span in line.spans:
span[SplitFlag.CROSS_PAGE] = True
def _is_cross_page_line(line: Line) -> bool:
"""判断整行是否来自跨页追加,供几何度量时排除。"""
- spans = line.get("spans", [])
+ spans = line.spans
return bool(spans) and all(span.get(SplitFlag.CROSS_PAGE) for span in spans)
-def _merge_ref_text_list_block(current_block, previous_block, is_cross_page):
+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
- previous_block.setdefault("blocks", []).extend(current_block.get("blocks", []))
+ previous_block.setdefault("blocks", []).extend(current_block.blocks)
current_block["blocks"] = []
current_block[SplitFlag.LINES_DELETED] = True
-def _line_height(line):
+def _line_height(line: Line) -> float:
bbox = line.get("bbox")
if not bbox:
return 0
return bbox[3] - bbox[1]
-def _build_bbox_fs(block, lines):
+def _build_bbox_fs(block: Block, lines: list[Line]) -> list[float]:
if lines:
return [
min(line["bbox"][0] for line in lines),
@@ -350,31 +336,31 @@ def _build_bbox_fs(block, lines):
return list(block.get("bbox", []))
-def _block_has_lines(block):
- return any(line.get("spans") for line in block.get("lines", []))
+def _block_has_lines(block: Block) -> bool:
+ return any(line.get("spans") for line in block.lines)
-def _first_non_empty_content(lines):
+def _first_non_empty_content(lines: list[Line]) -> str:
"""从行列表中提取第一个非空 span 文本,用于段落起始字符规则判断。"""
for line in lines:
- for span in line.get("spans", []):
+ for span in line.spans:
content = span.get("content", "")
if content:
return content
return ""
-def _last_non_empty_content(lines):
+def _last_non_empty_content(lines: list[Line]) -> str:
"""从行列表中提取最后一个非空 span 文本,用于段落结尾字符规则判断。"""
for line in reversed(lines):
- for span in reversed(line.get("spans", [])):
+ for span in reversed(line.spans):
content = span.get("content", "")
if content:
return content
return ""
-def _has_mergeable_block_bbox_relation(current_block, previous_block):
+def _has_mergeable_block_bbox_relation(current_block: Block, previous_block: Block) -> bool:
"""复刻 pipeline text 合并的核心几何条件:当前块上边界进入前块范围。"""
return current_block["bbox"][1] < previous_block["bbox"][3]
@@ -383,5 +369,5 @@ def _cleanup_block_internal_metadata(block: Block) -> None:
"""递归清理只供 finalize 内部流程使用的临时字段。"""
for metadata_key in INTERNAL_BLOCK_METADATA_KEYS:
block.pop(metadata_key, None)
- for sub_block in block.get("blocks", []):
+ for sub_block in block.blocks:
_cleanup_block_internal_metadata(sub_block)
diff --git a/mineru/backend/utils/runtime_utils.py b/mineru/backend/utils/runtime_utils.py
index 613db88b..4f292a17 100644
--- a/mineru/backend/utils/runtime_utils.py
+++ b/mineru/backend/utils/runtime_utils.py
@@ -1,13 +1,17 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import os
import time
+from typing import Any
from loguru import logger
-from mineru.utils.table_merge import merge_table
+from ...types import PageInfo
+from ...utils.table_merge import merge_table
-def cross_page_table_merge(pdf_info: list[dict]) -> None:
+def cross_page_table_merge(pdf_info: list[PageInfo]) -> None:
"""Merge tables that span across multiple pages in a PDF document.
Args:
@@ -16,13 +20,13 @@ def cross_page_table_merge(pdf_info: list[dict]) -> None:
Returns:
None
"""
- is_merge_table = os.getenv('MINERU_TABLE_MERGE_ENABLE', 'true')
- if is_merge_table.lower() in ['true', '1', 'yes']:
+ is_merge_table = os.getenv("MINERU_TABLE_MERGE_ENABLE", "true")
+ if is_merge_table.lower() in ["true", "1", "yes"]:
merge_table(pdf_info)
- elif is_merge_table.lower() in ['false', '0', 'no']:
+ elif is_merge_table.lower() in ["false", "0", "no"]:
pass
else:
- logger.warning(f'unknown MINERU_TABLE_MERGE_ENABLE config: {is_merge_table}, pass')
+ logger.warning(f"unknown MINERU_TABLE_MERGE_ENABLE config: {is_merge_table}, pass")
pass
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index 7b626c13..d47b5e84 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -1,7 +1,12 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import os
from typing import Any
+from mineru_vl_utils.structs import ExtractResult
+
+from ...data.data_reader_writer import DataWriter
from ...types import PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.cut_image import cut_image_and_table
@@ -11,6 +16,7 @@ from ...utils.pdfium_guard import pdfium_guard
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ...version import __version__
from ..utils.html_image_utils import replace_inline_table_images
+from ..utils.middle_json_utils import build_middle_json
from ..utils.para_block_utils import (
build_para_blocks_from_preproc,
cleanup_internal_para_block_metadata,
@@ -20,7 +26,13 @@ from ..utils.runtime_utils import cross_page_table_merge
from .vlm_magic_model import MagicModel
-def blocks_to_page_info(page_blocks: list, image_dict: dict, page: Any, image_writer: Any, page_index: int) -> PageInfo:
+def blocks_to_page_info(
+ page_blocks: ExtractResult,
+ image_dict: dict[str, Any],
+ page: Any,
+ image_writer: DataWriter | None,
+ page_index: int,
+) -> PageInfo:
"""将blocks转换为页面信息"""
scale = image_dict["scale"]
@@ -46,7 +58,7 @@ def blocks_to_page_info(page_blocks: list, image_dict: dict, page: Any, image_wr
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)
@@ -69,7 +81,6 @@ def blocks_to_page_info(page_blocks: list, image_dict: dict, page: Any, image_wr
# 对page_blocks根据index的值进行排序
page_blocks.sort(key=lambda x: x["index"])
-
page_info = PageInfo(
preproc_blocks=page_blocks,
discarded_blocks=discarded_blocks,
@@ -79,7 +90,7 @@ def blocks_to_page_info(page_blocks: list, image_dict: dict, page: Any, image_wr
return page_info
-def init_middle_json() -> dict:
+def init_middle_json() -> dict[str, Any]:
return {"pdf_info": [], "_backend": "vlm", "_version_name": __version__}
@@ -97,9 +108,12 @@ def finalize_middle_json(pdf_info_list: list[PageInfo]) -> None:
cleanup_internal_para_block_metadata(pdf_info_list)
-def result_to_middle_json(model_output_blocks_list: list, images_list: list, pdf_doc: Any, image_writer: Any) -> dict:
- from mineru.backend.utils.middle_json_utils import build_middle_json
-
+def result_to_middle_json(
+ model_output_blocks_list: list[list[dict[str, Any]]],
+ images_list: list[dict[str, Any]],
+ pdf_doc: Any,
+ image_writer: DataWriter,
+) -> dict[str, Any]:
return build_middle_json(
model_output_blocks_list,
images_list,
diff --git a/mineru/backend/vlm/utils.py b/mineru/backend/vlm/utils.py
index fc1d64d6..371b03fa 100644
--- a/mineru/backend/vlm/utils.py
+++ b/mineru/backend/vlm/utils.py
@@ -1,39 +1,40 @@
# Copyright (c) Opendatalab. All rights reserved.
+import json
import os
+from typing import Any
from loguru import logger
from packaging import version
-from mineru.utils.check_sys_env import is_windows_environment, is_linux_environment
-from mineru.utils.config_reader import get_device
-from mineru.utils.model_utils import get_vram
+from ...utils.check_sys_env import is_linux_environment, is_windows_environment
+from ...utils.config_reader import get_device
+from ...utils.model_utils import get_vram
def enable_custom_logits_processors() -> bool:
import torch
- from vllm import __version__ as vllm_version
+ from vllm import __version__ as vllm_version # type: ignore
if torch.cuda.is_available():
major, minor = torch.cuda.get_device_capability()
# 正确计算Compute Capability
compute_capability = f"{major}.{minor}"
- elif hasattr(torch, 'npu') and torch.npu.is_available():
+ elif hasattr(torch, "npu") and torch.npu.is_available(): # type: ignore
compute_capability = "8.0"
- elif hasattr(torch, 'gcu') and torch.gcu.is_available():
+ elif hasattr(torch, "gcu") and torch.gcu.is_available(): # type: ignore
compute_capability = "8.0"
- elif hasattr(torch, 'musa') and torch.musa.is_available():
+ elif hasattr(torch, "musa") and torch.musa.is_available(): # type: ignore
compute_capability = "8.0"
- elif hasattr(torch, 'mlu') and torch.mlu.is_available():
+ elif hasattr(torch, "mlu") and torch.mlu.is_available(): # type: ignore
compute_capability = "8.0"
- elif hasattr(torch, 'sdaa') and torch.sdaa.is_available():
+ elif hasattr(torch, "sdaa") and torch.sdaa.is_available(): # type: ignore
compute_capability = "8.0"
-
else:
logger.info("CUDA not available, disabling custom_logits_processors")
return False
# 安全地处理环境变量
- vllm_use_v1_str = os.getenv('VLLM_USE_V1', "1")
+ vllm_use_v1_str = os.getenv("VLLM_USE_V1", "1")
if vllm_use_v1_str.isdigit():
vllm_use_v1 = int(vllm_use_v1_str)
else:
@@ -47,13 +48,22 @@ def enable_custom_logits_processors() -> bool:
return False
elif version.parse(compute_capability) < version.parse("8.0"):
if version.parse(vllm_version) >= version.parse("0.10.2"):
- logger.info(f"compute_capability: {compute_capability} < 8.0, but vllm version: {vllm_version} >= 0.10.2, enable custom_logits_processors")
+ logger.info(
+ f"compute_capability: {compute_capability} < 8.0, but vllm version: {vllm_version} >= 0.10.2,"
+ " enable custom_logits_processors"
+ )
return True
else:
- logger.info(f"compute_capability: {compute_capability} < 8.0 and vllm version: {vllm_version} < 0.10.2, disable custom_logits_processors")
+ logger.info(
+ f"compute_capability: {compute_capability} < 8.0 and vllm version: {vllm_version} < 0.10.2,"
+ " disable custom_logits_processors"
+ )
return False
else:
- logger.info(f"compute_capability: {compute_capability} >= 8.0 and vllm version: {vllm_version} >= 0.10.1, enable custom_logits_processors")
+ logger.info(
+ f"compute_capability: {compute_capability} >= 8.0 and vllm version: {vllm_version} >= 0.10.1,"
+ " enable custom_logits_processors"
+ )
return True
@@ -62,6 +72,7 @@ def set_lmdeploy_backend(device_type: str) -> str:
lmdeploy_backend = "pytorch"
elif device_type.lower() in ["cuda"]:
import torch
+
if not torch.cuda.is_available():
raise ValueError("CUDA is not available.")
if is_windows_environment():
@@ -81,14 +92,18 @@ def set_lmdeploy_backend(device_type: str) -> str:
def set_default_gpu_memory_utilization() -> float:
- from vllm import __version__ as vllm_version
+ from vllm import __version__ as vllm_version # type: ignore
+
device = get_device()
gpu_memory = get_vram(device)
default_gpu_memory_utilization = 0.5
if version.parse(vllm_version) >= version.parse("0.11.0") and gpu_memory <= 8:
default_gpu_memory_utilization = 0.7
- logger.debug(f"vllm_version: {vllm_version}, gpu_memory: {gpu_memory} GB, default_gpu_memory_utilization: {default_gpu_memory_utilization}")
+ logger.debug(
+ f"vllm_version: {vllm_version}, gpu_memory: {gpu_memory} GB,"
+ f" default_gpu_memory_utilization: {default_gpu_memory_utilization}"
+ )
return default_gpu_memory_utilization
@@ -103,10 +118,10 @@ def set_default_batch_size() -> int:
batch_size = 4
else:
batch_size = 1
- logger.info(f'gpu_memory: {gpu_memory} GB, batch_size: {batch_size}')
+ logger.info(f"gpu_memory: {gpu_memory} GB, batch_size: {batch_size}")
except Exception as e:
- logger.warning(f'Error determining VRAM: {e}, using default batch_ratio: 1')
+ logger.warning(f"Error determining VRAM: {e}, using default batch_ratio: 1")
batch_size = 1
return batch_size
@@ -126,16 +141,22 @@ def _get_device_config(device_type: str) -> dict | None:
"corex": {
"compilation_config_dict": {
"cudagraph_mode": "FULL_DECODE_ONLY",
- "level": 0
+ "level": 0,
},
},
"kxpu": {
"compilation_config_dict": {
"splitting_ops": [
- "vllm.unified_attention", "vllm.unified_attention_with_output",
- "vllm.unified_attention_with_output_kunlun", "vllm.mamba_mixer2",
- "vllm.mamba_mixer", "vllm.short_conv", "vllm.linear_attention",
- "vllm.plamo2_mamba_mixer", "vllm.gdn_attention", "vllm.sparse_attn_indexer"
+ "vllm.unified_attention",
+ "vllm.unified_attention_with_output",
+ "vllm.unified_attention_with_output_kunlun",
+ "vllm.mamba_mixer2",
+ "vllm.mamba_mixer",
+ "vllm.short_conv",
+ "vllm.linear_attention",
+ "vllm.plamo2_mamba_mixer",
+ "vllm.gdn_attention",
+ "vllm.sparse_attn_indexer",
]
},
"block_size": 128,
@@ -149,30 +170,30 @@ def _get_device_config(device_type: str) -> dict | None:
return DEVICE_CONFIGS.get(device_type.lower())
-def _check_server_arg_exists(args: list, arg_name: str) -> bool:
+def _check_server_arg_exists(args: list[str], arg_name: str) -> bool:
"""检查命令行参数列表中是否已存在指定参数"""
return any(arg == f"--{arg_name}" or arg.startswith(f"--{arg_name}=") for arg in args)
-def _add_server_arg_if_missing(args: list, arg_name: str, value: str) -> None:
+def _add_server_arg_if_missing(args: list[str], arg_name: str, value: str) -> None:
"""如果参数不存在,则添加到命令行参数列表"""
if not _check_server_arg_exists(args, arg_name):
args.extend([f"--{arg_name}", value])
-def _add_server_flag_if_missing(args: list, flag_name: str) -> None:
+def _add_server_flag_if_missing(args: list[str], flag_name: str) -> None:
"""如果 flag 不存在,则添加到命令行参数列表"""
if not _check_server_arg_exists(args, flag_name):
args.append(f"--{flag_name}")
-def _add_engine_kwarg_if_missing(kwargs: dict, key: str, value: Any) -> None:
+def _add_engine_kwarg_if_missing(kwargs: dict[str, Any], key: str, value: object) -> None:
"""如果参数不存在,则添加到 kwargs 字典"""
if key not in kwargs:
kwargs[key] = value
-def mod_kwargs_by_device_type(kwargs_or_args: dict | list, vllm_mode: str) -> dict | list:
+def mod_kwargs_by_device_type(kwargs_or_args: dict[str, Any] | list[str], vllm_mode: str) -> dict[str, Any] | list[str]:
"""根据设备类型修改 vllm 配置参数
Args:
@@ -196,16 +217,11 @@ def mod_kwargs_by_device_type(kwargs_or_args: dict | list, vllm_mode: str) -> di
return kwargs_or_args
-def _apply_server_config(args: list, config: dict) -> None:
+def _apply_server_config(args: list[str], config: dict[str, Any]) -> None:
"""应用 server 模式的配置"""
- import json
-
for key, value in config.items():
if key == "compilation_config_dict":
- _add_server_arg_if_missing(
- args, "compilation-config",
- json.dumps(value, separators=(',', ':'))
- )
+ _add_server_arg_if_missing(args, "compilation-config", json.dumps(value, separators=(",", ":")))
else:
# 转换 key 格式: block_size -> block-size
arg_name = key.replace("_", "-")
@@ -215,10 +231,10 @@ def _apply_server_config(args: list, config: dict) -> None:
_add_server_arg_if_missing(args, arg_name, str(value))
-def _apply_engine_config(kwargs: dict, config: dict, vllm_mode: str) -> None:
+def _apply_engine_config(kwargs: dict[str, Any], config: dict[str, Any], vllm_mode: str) -> None:
"""应用 engine 模式的配置"""
try:
- from vllm.config import CompilationConfig
+ from vllm.config import CompilationConfig # type: ignore
except ImportError:
raise ImportError("Please install vllm to use the vllm-async-engine backend.")
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index 3b33f266..4f30ae00 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -1,44 +1,40 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import asyncio
import atexit
import gc
-import os
-import time
import json
+import os
import threading
+import time
from contextlib import asynccontextmanager, contextmanager
+from typing import Any, Generator, Iterator
import pypdfium2 as pdfium
from loguru import logger
+from mineru_vl_utils import MinerUClient
+from mineru_vl_utils.structs import ExtractResult
+from packaging import version
from tqdm import tqdm
-from .utils import enable_custom_logits_processors, set_default_gpu_memory_utilization, set_default_batch_size, \
- set_lmdeploy_backend, mod_kwargs_by_device_type
-from .model_output_to_middle_json import (
- blocks_to_page_info,
- finalize_middle_json,
- init_middle_json,
-)
-from mineru.backend.utils.middle_json_utils import append_pages
-from mineru.backend.utils.runtime_utils import exclude_progress_bar_idle_time
from ...data.data_reader_writer import DataWriter
-from mineru.utils.pdf_image_tools import (
- aio_load_images_from_pdf_bytes_range,
- load_images_from_pdf_doc,
-)
from ...utils.check_sys_env import is_mac_os_version_supported
from ...utils.config_reader import get_device, get_processing_window_size
-
from ...utils.enum_class import ImageType
-from ...utils.pdfium_guard import (
- close_pdfium_document,
- get_pdfium_document_page_count,
- open_pdfium_document,
-)
from ...utils.models_download_utils import auto_download_and_get_model_root_path
-
-from mineru_vl_utils import MinerUClient
-from packaging import version
+from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_doc
+from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ..utils.middle_json_utils import append_pages
+from ..utils.runtime_utils import exclude_progress_bar_idle_time
+from .model_output_to_middle_json import blocks_to_page_info, finalize_middle_json, init_middle_json
+from .utils import (
+ enable_custom_logits_processors,
+ mod_kwargs_by_device_type,
+ set_default_batch_size,
+ set_default_gpu_memory_utilization,
+ set_lmdeploy_backend,
+)
class ModelSingleton:
@@ -46,7 +42,7 @@ class ModelSingleton:
_models = {}
_lock = threading.RLock()
- def __new__(cls, *args, **kwargs):
+ def __new__(cls, *args: object, **kwargs: object) -> ModelSingleton:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
@@ -57,7 +53,7 @@ class ModelSingleton:
backend: str,
model_path: str | None,
server_url: str | None,
- **kwargs,
+ **kwargs: Any,
) -> MinerUClient:
key = (backend, model_path, server_url)
with self._lock:
@@ -75,11 +71,18 @@ class ModelSingleton:
max_retries = kwargs.get("max_retries", 3) # for http-client backend only
retry_backoff_factor = kwargs.get("retry_backoff_factor", 0.5) # for http-client backend only
# 从kwargs中移除这些参数,避免传递给不相关的初始化函数
- for param in ["batch_size", "max_concurrency", "http_timeout", "server_headers", "max_retries", "retry_backoff_factor"]:
+ for param in [
+ "batch_size",
+ "max_concurrency",
+ "http_timeout",
+ "server_headers",
+ "max_retries",
+ "retry_backoff_factor",
+ ]:
if param in kwargs:
del kwargs[param]
if backend not in ["http-client"] and not model_path:
- model_path = auto_download_and_get_model_root_path("/","vlm")
+ model_path = auto_download_and_get_model_root_path("/", "vlm")
if backend == "transformers":
try:
from transformers import (
@@ -111,9 +114,10 @@ class ModelSingleton:
if not mlx_supported:
raise EnvironmentError("mlx-engine backend is only supported on macOS 13.5+ with Apple Silicon.")
from mineru_vl_utils.mlx_compat import load_mlx_model
+
model, processor = load_mlx_model(model_path)
else:
- if os.getenv('OMP_NUM_THREADS') is None:
+ if os.getenv("OMP_NUM_THREADS") is None:
os.environ["OMP_NUM_THREADS"] = "1"
if backend == "vllm-engine":
@@ -130,7 +134,8 @@ class ModelSingleton:
kwargs["compilation_config"] = json.loads(kwargs["compilation_config"])
except json.JSONDecodeError:
logger.warning(
- f"Failed to parse compilation_config as JSON: {kwargs['compilation_config']}")
+ f"Failed to parse compilation_config as JSON: {kwargs['compilation_config']}"
+ )
del kwargs["compilation_config"]
if "gpu_memory_utilization" not in kwargs:
kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
@@ -138,14 +143,15 @@ class ModelSingleton:
kwargs["model"] = model_path
if enable_custom_logits_processors() and ("logits_processors" not in kwargs):
from mineru_vl_utils import MinerULogitsProcessor
+
kwargs["logits_processors"] = [MinerULogitsProcessor]
# 使用kwargs为 vllm初始化参数
vllm_llm = vllm.LLM(**kwargs)
elif backend == "vllm-async-engine":
try:
+ from vllm.config import CompilationConfig
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.v1.engine.async_llm import AsyncLLM
- from vllm.config import CompilationConfig
except ImportError:
raise ImportError("Please install vllm to use the vllm-async-engine backend.")
@@ -162,7 +168,8 @@ class ModelSingleton:
kwargs["compilation_config"] = CompilationConfig(**config_dict)
except (json.JSONDecodeError, TypeError) as e:
logger.warning(
- f"Failed to parse compilation_config: {kwargs['compilation_config']}, error: {e}")
+ f"Failed to parse compilation_config: {kwargs['compilation_config']}, error: {e}"
+ )
del kwargs["compilation_config"]
if "gpu_memory_utilization" not in kwargs:
kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
@@ -170,6 +177,7 @@ class ModelSingleton:
kwargs["model"] = model_path
if enable_custom_logits_processors() and ("logits_processors" not in kwargs):
from mineru_vl_utils import MinerULogitsProcessor
+
kwargs["logits_processors"] = [MinerULogitsProcessor]
# 使用kwargs为 vllm初始化参数
vllm_async_llm = AsyncLLM.from_engine_args(AsyncEngineArgs(**kwargs))
@@ -208,12 +216,13 @@ class ModelSingleton:
else:
raise ValueError(f"Unsupported lmdeploy backend: {lm_backend}")
- log_level = 'ERROR'
+ log_level = "ERROR"
from lmdeploy.utils import get_logger
- lm_logger = get_logger('lmdeploy')
+
+ lm_logger = get_logger("lmdeploy")
lm_logger.setLevel(log_level)
- if os.getenv('TM_LOG_LEVEL') is None:
- os.environ['TM_LOG_LEVEL'] = log_level
+ if os.getenv("TM_LOG_LEVEL") is None:
+ os.environ["TM_LOG_LEVEL"] = log_level
lmdeploy_engine = VLAsyncEngine(
model_path,
@@ -267,7 +276,7 @@ async def _get_model_async(
backend: str,
model_path: str | None,
server_url: str | None,
- **kwargs,
+ **kwargs: Any,
) -> MinerUClient:
return await asyncio.to_thread(
ModelSingleton().get_model,
@@ -278,7 +287,7 @@ async def _get_model_async(
)
-def _iter_shutdown_candidates(predictor: MinerUClient) -> list:
+def _iter_shutdown_candidates(predictor: MinerUClient) -> Generator[object, None, None]:
runtime_handles = getattr(predictor, "_mineru_runtime_handles", {})
client = getattr(predictor, "client", None)
@@ -301,7 +310,7 @@ def _iter_shutdown_candidates(predictor: MinerUClient) -> list:
yield from _yield_candidate(getattr(client, key, None))
-def _call_nested_shutdown(target, method_path: str, label: str) -> bool:
+def _call_nested_shutdown(target: object, method_path: str, label: str) -> bool:
current = target
for attr in method_path.split("."):
current = getattr(current, attr, None)
@@ -323,7 +332,7 @@ def _call_nested_shutdown(target, method_path: str, label: str) -> bool:
return False
-def _shutdown_runtime_handle(handle) -> None:
+def _shutdown_runtime_handle(handle: object) -> None:
for method_path in (
"shutdown",
"close",
@@ -381,9 +390,7 @@ 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"
- ):
+ if _predictor_uses_mlx(predictor, backend) and not hasattr(predictor, "_mineru_execution_lock"):
predictor._mineru_execution_lock = threading.Lock()
return predictor
@@ -411,7 +418,7 @@ async def aio_predictor_execution_guard(predictor: MinerUClient) -> None:
lock.release()
-def _close_images(images_list: list) -> None:
+def _close_images(images_list: list[dict[str, Any]]) -> None:
for image_dict in images_list or []:
pil_img = image_dict.get("img_pil")
if pil_img is not None:
@@ -422,38 +429,32 @@ def _close_images(images_list: list) -> None:
def doc_analyze(
- pdf_bytes,
+ pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend="transformers",
+ backend: str = "transformers",
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
- **kwargs,
-):
- client_side_output_generation = bool(
- kwargs.pop("client_side_output_generation", False)
- )
+ **kwargs: Any,
+) -> tuple[dict[str, object], list[list[dict[str, object]]]]:
+ client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
if predictor is None:
predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
predictor = _maybe_enable_serial_execution(predictor, backend)
pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
middle_json = init_middle_json()
- results = []
+ results: list[ExtractResult] = []
doc_closed = False
try:
page_count = get_pdfium_document_page_count(pdf_doc)
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
- total_windows = (
- (page_count + effective_window_size - 1) // effective_window_size
- if effective_window_size
- else 0
- )
+ total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
logger.info(
- f'VLM processing-window run. page_count={page_count}, '
- f'window_size={configured_window_size}, total_windows={total_windows}'
+ f"VLM processing-window run. page_count={page_count}, "
+ f"window_size={configured_window_size}, total_windows={total_windows}"
)
infer_start = time.time()
@@ -472,9 +473,9 @@ def doc_analyze(
try:
images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
logger.info(
- f'VLM processing window {window_index + 1}/{total_windows}: '
- f'pages {window_start + 1}-{window_end + 1}/{page_count} '
- f'({len(images_pil_list)} pages)'
+ f"VLM processing window {window_index + 1}/{total_windows}: "
+ f"pages {window_start + 1}-{window_end + 1}/{page_count} "
+ f"({len(images_pil_list)} pages)"
)
with predictor_execution_guard(predictor):
window_results = predictor.batch_two_step_extract(
@@ -509,8 +510,7 @@ def doc_analyze(
infer_time = round(time.time() - infer_start, 2)
if infer_time > 0 and page_count > 0:
logger.debug(
- f"processing-window infer finished, cost: {infer_time}, "
- f"speed: {round(len(results) / infer_time, 3)} page/s"
+ f"processing-window infer finished, cost: {infer_time}, speed: {round(len(results) / infer_time, 3)} page/s"
)
if not client_side_output_generation:
finalize_middle_json(middle_json["pdf_info"])
@@ -523,18 +523,16 @@ def doc_analyze(
async def aio_doc_analyze(
- pdf_bytes,
+ pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend="transformers",
+ backend: str = "transformers",
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
- **kwargs,
-):
- client_side_output_generation = bool(
- kwargs.pop("client_side_output_generation", False)
- )
+ **kwargs: Any,
+) -> tuple[dict[str, object], list[list[dict[str, object]]]]:
+ client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
if predictor is None:
predictor = await _get_model_async(backend, model_path, server_url, **kwargs)
predictor = _maybe_enable_serial_execution(predictor, backend)
@@ -547,14 +545,10 @@ async def aio_doc_analyze(
page_count = get_pdfium_document_page_count(pdf_doc)
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
- total_windows = (
- (page_count + effective_window_size - 1) // effective_window_size
- if effective_window_size
- else 0
- )
+ total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
logger.info(
- f'VLM processing-window run. page_count={page_count}, '
- f'window_size={configured_window_size}, total_windows={total_windows}'
+ f"VLM processing-window run. page_count={page_count}, "
+ f"window_size={configured_window_size}, total_windows={total_windows}"
)
infer_start = time.time()
@@ -572,9 +566,9 @@ async def aio_doc_analyze(
try:
images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
logger.info(
- f'VLM processing window {window_index + 1}/{total_windows}: '
- f'pages {window_start + 1}-{window_end + 1}/{page_count} '
- f'({len(images_pil_list)} pages)'
+ f"VLM processing window {window_index + 1}/{total_windows}: "
+ f"pages {window_start + 1}-{window_end + 1}/{page_count} "
+ f"({len(images_pil_list)} pages)"
)
async with aio_predictor_execution_guard(predictor):
window_results = await predictor.aio_batch_two_step_extract(
@@ -609,8 +603,7 @@ async def aio_doc_analyze(
infer_time = round(time.time() - infer_start, 2)
if infer_time > 0 and page_count > 0:
logger.debug(
- f"processing-window infer finished, cost: {infer_time}, "
- f"speed: {round(len(results) / infer_time, 3)} page/s"
+ f"processing-window infer finished, cost: {infer_time}, speed: {round(len(results) / infer_time, 3)} page/s"
)
if not client_side_output_generation:
await asyncio.to_thread(finalize_middle_json, middle_json["pdf_info"])
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index a7cfe1c0..85523855 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -1,7 +1,10 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import re
from loguru import logger
+from mineru_vl_utils.structs import ContentBlock, ExtractResult
from ...types import Block, Line, Span
from ...utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
@@ -20,7 +23,7 @@ from ...utils.visual_magic_model_utils import (
)
-def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict, block: Block) -> None:
+def _copy_raw_text_block_metadata(raw_block_type: str, block_info: ContentBlock, block: Block) -> None:
if raw_block_type != BlockType.TEXT:
return
if "merge_prev" in block_info:
@@ -28,14 +31,14 @@ def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict, block:
class MagicModel:
- def __init__(self, page_blocks: list, width: int, height: int) -> None:
+ def __init__(self, page_blocks: ExtractResult, width: int, height: int) -> None:
self.page_blocks = page_blocks
blocks = []
self.all_spans = []
# 解析每个块
- for index, block_info in enumerate(page_blocks):
- block_bbox = block_info["bbox"]
+ for index, content_block in enumerate(page_blocks):
+ block_bbox = content_block["bbox"]
try:
x1, y1, x2, y2 = block_bbox
x_1, y_1, x_2, y_2 = (
@@ -49,14 +52,14 @@ class MagicModel:
if y_2 < y_1:
y_1, y_2 = y_2, y_1
block_bbox = (x_1, y_1, x_2, y_2)
- block_type = block_info["type"]
+ block_type = content_block["type"]
raw_block_type = block_type
- block_content = block_info.get("content")
- block_angle = block_info.get("angle", 0)
- block_sub_type = block_info.get("sub_type") if raw_block_type in ["image", "chart"] else None
+ block_content = content_block.get("content", "")
+ block_angle = content_block.get("angle", 0)
+ block_sub_type = content_block.get("sub_type") if raw_block_type in ["image", "chart"] else None
except Exception as e:
# 如果解析失败,可能是因为格式不正确,跳过这个块
- logger.warning(f"Invalid block format: {block_info}, error: {e}")
+ logger.warning(f"Invalid block format: {content_block}, error: {e}")
continue
span_type = "unknown"
@@ -114,9 +117,9 @@ class MagicModel:
if span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:
span = Span(type=span_type, bbox=block_bbox)
if span_type == ContentType.TABLE:
- span["html"] = block_content
+ span.html = block_content
elif raw_block_type in ["image", "chart"] and block_content is not None:
- span["content"] = block_content
+ span.content = block_content
elif span_type == ContentType.INTERLINE_EQUATION:
span = Span(
type=span_type,
@@ -203,21 +206,19 @@ class MagicModel:
if block_type == BlockType.CODE_BODY:
if switch_code_to_algorithm and code_block_sub_type == "code":
code_block_sub_type = "algorithm"
- line = Line(spans=spans)
- line["bbox"] = block_bbox
+ line = Line(spans=spans, bbox=block_bbox)
line["extra"] = {"type": code_block_sub_type, "guess_lang": guess_lang}
else:
- line = Line(spans=spans)
- line["bbox"] = block_bbox
+ line = Line(spans=spans, bbox=block_bbox)
block = Block(type=block_type, bbox=block_bbox, lines=[line])
block["angle"] = block_angle
block["index"] = index
if 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"]
- _copy_raw_text_block_metadata(raw_block_type, block_info, block)
+ if raw_block_type == "table" and "cell_merge" in content_block:
+ block["cell_merge"] = content_block["cell_merge"]
+ _copy_raw_text_block_metadata(raw_block_type, content_block, block)
blocks.append(block)
@@ -326,24 +327,18 @@ class MagicModel:
return self.all_spans
-def fix_list_blocks(list_blocks: list[Block], text_blocks: list[Block], ref_text_blocks: list[Block]) -> tuple[list[Block], list[Block], list[Block]]:
+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.lines = []
temp_text_blocks = text_blocks + ref_text_blocks
need_remove_blocks = []
for block in temp_text_blocks:
for list_block in list_blocks:
- if (
- calculate_overlap_area_in_bbox1_area_ratio(
- block["bbox"],
- list_block["bbox"],
- )
- >= 0.8
- ):
- list_block["blocks"].append(block)
+ if calculate_overlap_area_in_bbox1_area_ratio(block.bbox, list_block.bbox) >= 0.8:
+ list_block.blocks.append(block)
need_remove_blocks.append(block)
break
@@ -354,20 +349,20 @@ def fix_list_blocks(list_blocks: list[Block], text_blocks: list[Block], ref_text
ref_text_blocks.remove(block)
# 移除blocks为空的list_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:
# 统计list_block["blocks"]中所有block的type,用众数作为list_block的sub_type
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) # type: ignore
else:
- list_block["sub_type"] = "unknown"
+ list_block.sub_type = "unknown"
return list_blocks, text_blocks, ref_text_blocks
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index a08198cb..9a977004 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -1,33 +1,30 @@
# Copyright (c) Opendatalab. All rights reserved.
import os
import re
-from html import escape, unescape
+from html import unescape
from loguru import logger
-from mineru.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
-from mineru.utils.config_reader import get_latex_delimiter_config, get_formula_enable, get_table_enable
-from mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2
-from mineru.types import Block
-from mineru.utils.language import detect_lang
-from mineru.backend.utils.markdown_utils import (
- escape_conservative_markdown_text,
- escape_text_block_markdown_prefix,
-)
+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.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
latex_delimiters_config = get_latex_delimiter_config()
default_delimiters = {
- 'display': {'left': '$$', 'right': '$$'},
- 'inline': {'left': '$', 'right': '$'}
+ "display": {"left": "$$", "right": "$$"},
+ "inline": {"left": "$", "right": "$"},
}
delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
-display_left_delimiter = delimiters['display']['left']
-display_right_delimiter = delimiters['display']['right']
-inline_left_delimiter = delimiters['inline']['left']
-inline_right_delimiter = delimiters['inline']['right']
+display_left_delimiter = delimiters["display"]["left"]
+display_right_delimiter = delimiters["display"]["right"]
+inline_left_delimiter = delimiters["inline"]["left"]
+inline_right_delimiter = delimiters["inline"]["right"]
def _prefix_table_img_src(html: str, img_buket_path: str) -> str:
@@ -48,10 +45,8 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
return html
return re.sub(
- r'<eq>(.*?)</eq>',
- lambda match: (
- f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} "
- ),
+ r"<eq>(.*?)</eq>",
+ lambda match: f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} ",
html,
flags=re.DOTALL,
)
@@ -65,62 +60,59 @@ def _format_embedded_html(html: str, img_buket_path: str) -> str:
def _normalize_text_content(content: str | None) -> str:
"""将 VLM 文本 span 的空 content 规范为空字符串,再做全角转半角。"""
if content is None:
- return ''
+ return ""
return full_to_half_exclude_marks(content)
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.get("spans", [])[start_span_idx:]:
+ next_span_type = next_span.get("type")
if next_span_type == ContentType.TEXT:
- if _normalize_text_content(next_span.get('content')).strip():
+ if _normalize_text_content(next_span.get("content")).strip():
return True
elif next_span_type == ContentType.INLINE_EQUATION:
- if str(next_span.get('content', '')).strip():
+ if str(next_span.get("content", "")).strip():
return True
return False
def _build_media_path(img_buket_path: str, image_path: str) -> str:
if not image_path:
- return ''
+ return ""
if not img_buket_path:
return image_path
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')
+ sub_type = para_block.get("sub_type")
if sub_type:
- para_content['sub_type'] = sub_type
+ para_content["sub_type"] = sub_type
-def _build_visual_details_block(content: str, span_type: str, summary_override: str = '') -> str:
+def _build_visual_details_block(content: str, span_type: str, summary_override: str = "") -> str:
if not isinstance(content, str) or not content.strip():
- return ''
+ return ""
if span_type == ContentType.CHART:
summary = summary_override or "chart content"
else:
summary = summary_override or "image content"
- return (
- "<details>\n"
- f"<summary>{summary}</summary>\n\n"
- f"{content}\n"
- "</details>"
- )
+ return f"<details>\n<summary>{summary}</summary>\n\n{content}\n</details>"
-def _build_visual_body_segments(image_path: str, content: str, img_buket_path: str, span_type: str, summary_override: str = '') -> list[tuple[str, str]]:
+def _build_visual_body_segments(
+ image_path: str, content: str, img_buket_path: str, span_type: str, summary_override: str = ""
+) -> list[tuple[str, str]]:
body_segments = []
media_path = _build_media_path(img_buket_path, image_path)
if media_path:
- body_segments.append((f"![]({media_path})", 'markdown_line'))
+ body_segments.append((f"![]({media_path})", "markdown_line"))
details_block = _build_visual_details_block(
content,
@@ -128,7 +120,7 @@ def _build_visual_body_segments(image_path: str, content: str, img_buket_path: s
summary_override=summary_override,
)
if details_block:
- body_segments.append((details_block, 'html_block'))
+ body_segments.append((details_block, "html_block"))
return body_segments
@@ -138,21 +130,23 @@ 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].get("index", float("inf")), 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.get("sub_type") == BlockType.CODE:
+ guess_lang = para_block.get("guess_lang", "txt")
return f"```{guess_lang}\n{code_text}\n```"
return code_text
-def _render_visual_block_segments(block: Block, para_block: Block, img_buket_path: str = '', table_enable: bool = True) -> list[tuple[str, str]]:
- block_type = block['type']
+def _render_visual_block_segments(
+ block: Block, para_block: Block, img_buket_path: str = "", table_enable: bool = True
+) -> list[tuple[str, str]]:
+ block_type = block.type
if block_type in [
BlockType.IMAGE_CAPTION,
@@ -166,79 +160,83 @@ def _render_visual_block_segments(block: Block, para_block: Block, img_buket_pat
]:
block_text = merge_para_with_text(block)
if block_text.strip():
- return [(block_text, 'markdown_line')]
+ return [(block_text, "markdown_line")]
return []
if block_type == BlockType.IMAGE_BODY:
rendered_segments = []
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- if span.get('type') != ContentType.IMAGE:
+ for line in block.lines:
+ for span in line.spans:
+ if span.get("type") != ContentType.IMAGE:
continue
rendered_segments.extend(
_build_visual_body_segments(
- span.get('image_path', ''),
- span.get('content', ''),
+ span.get("image_path", ""),
+ span.get("content", ""),
img_buket_path,
ContentType.IMAGE,
- summary_override=para_block.get('sub_type', ''),
+ summary_override=para_block.get("sub_type", ""),
)
)
return rendered_segments
if block_type == BlockType.CHART_BODY:
rendered_segments = []
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- if span.get('type') != ContentType.CHART:
+ for line in block.lines:
+ for span in line.spans:
+ if span.get("type") != ContentType.CHART:
continue
rendered_segments.extend(
_build_visual_body_segments(
- span.get('image_path', ''),
- span.get('content', ''),
+ span.get("image_path", ""),
+ span.get("content", ""),
img_buket_path,
ContentType.CHART,
- summary_override=para_block.get('sub_type', ''),
+ summary_override=para_block.get("sub_type", ""),
)
)
return rendered_segments
if block_type == BlockType.TABLE_BODY:
rendered_segments = []
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- if span.get('type') != ContentType.TABLE:
+ for line in block.lines:
+ for span in line.spans:
+ if span.get("type") != ContentType.TABLE:
continue
- if table_enable and span.get('html', ''):
- rendered_segments.append((
- _format_embedded_html(span['html'], img_buket_path),
- 'html_block',
- ))
- elif span.get('image_path', ''):
- rendered_segments.append((
- f"![]({_build_media_path(img_buket_path, span['image_path'])})",
- 'markdown_line',
- ))
+ if table_enable and span.get("html", ""):
+ rendered_segments.append(
+ (
+ _format_embedded_html(span["html"], img_buket_path),
+ "html_block",
+ )
+ )
+ elif span.get("image_path", ""):
+ rendered_segments.append(
+ (
+ f"![]({_build_media_path(img_buket_path, span['image_path'])})",
+ "markdown_line",
+ )
+ )
return rendered_segments
if block_type == BlockType.CODE_BODY:
block_text = _render_code_block_markdown(block, para_block)
if block_text.strip():
- return [(block_text, 'markdown_line')]
+ return [(block_text, "markdown_line")]
return []
return []
def _get_visual_block_separator(prev_segment_kind: str, current_segment_kind: str) -> str:
- if prev_segment_kind == 'html_block' or current_segment_kind == 'html_block':
- return '\n\n'
- return ' \n'
+ if prev_segment_kind == "html_block" or current_segment_kind == "html_block":
+ return "\n\n"
+ return " \n"
-def _merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = '', table_enable: bool = True) -> str:
+def _merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = "", table_enable: bool = True) -> str:
rendered_segments = []
- for block in _get_blocks_in_index_order(para_block.get('blocks', [])):
+ for block in _get_blocks_in_index_order(para_block.blocks):
rendered_segments.extend(
_render_visual_block_segments(
block,
@@ -248,7 +246,7 @@ def _merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = ''
)
)
- para_text = ''
+ para_text = ""
prev_segment_kind = None
for segment_text, segment_kind in rendered_segments:
if para_text:
@@ -259,23 +257,28 @@ def _merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = ''
return para_text
-def merge_para_with_text(para_block: Block, formula_enable: bool = True, img_buket_path: str = '', escape_text_block_prefix: bool = True) -> 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'))
- block_text += span['content']
+def merge_para_with_text(
+ para_block: Block,
+ formula_enable: bool = True,
+ img_buket_path: str = "",
+ escape_text_block_prefix: bool = True,
+) -> 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.content)
+ block_text += span.content
block_lang = detect_lang(block_text)
- escape_markdown_text = para_block.get('type') != BlockType.CODE_BODY
+ 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']
- content = ''
+ para_text = ""
+ 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']
+ content = span["content"]
if escape_markdown_text:
content = escape_conservative_markdown_text(content)
elif span_type == ContentType.INLINE_EQUATION:
@@ -284,71 +287,65 @@ def merge_para_with_text(para_block: Block, formula_enable: bool = True, img_buk
if formula_enable:
content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
else:
- if span.get('image_path', ''):
+ if span.get("image_path", ""):
content = f"![]({img_buket_path}/{span['image_path']})"
content = content.strip()
if content:
-
if span_type == ContentType.INTERLINE_EQUATION:
para_text += content
continue
# 定义CJK语言集合(中日韩)
- cjk_langs = {'zh', 'ja', 'ko'}
+ cjk_langs = {"zh", "ja", "ko"}
# 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: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
- if (
- has_following_joinable_span
- and (not is_last_span or span_type == ContentType.INLINE_EQUATION)
- ):
- para_text += f'{content} '
+ if has_following_joinable_span and (not is_last_span or span_type == ContentType.INLINE_EQUATION):
+ para_text += f"{content} "
else:
para_text += content
else:
# 西方文本语境下 每行的最后一个span判断是否要去除连字符
if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:
# 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
- if (
- is_last_span
- and span_type == ContentType.TEXT
- and is_hyphen_at_line_end(content)
- ):
+ 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不是小写字母开头,则保留连字符但不加空格
para_text += content
else: # 西方文本语境下 content间需要空格分隔
if has_following_joinable_span:
- para_text += f'{content} '
+ para_text += f"{content} "
else:
para_text += content
- if escape_text_block_prefix and para_block.get('type') == BlockType.TEXT:
+ if escape_text_block_prefix and para_block.type == BlockType.TEXT:
para_text = escape_text_block_markdown_prefix(para_text)
return para_text
-def mk_blocks_to_markdown(para_blocks: list[Block], make_mode: str, formula_enable: bool, table_enable: bool, img_buket_path: str = '') -> str:
- page_markdown = []
+def mk_blocks_to_markdown(
+ para_blocks: list[Block], make_mode: str, formula_enable: bool, table_enable: bool, img_buket_path: str = ""
+) -> list[str]:
+ page_markdown: list[str] = []
for para_block in para_blocks:
- para_text = ''
- para_type = para_block['type']
+ para_text = ""
+ para_type = para_block.type
if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:
para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_buket_path=img_buket_path)
elif para_type == BlockType.LIST:
- for block in para_block['blocks']:
+ for block in para_block.blocks:
item_text = merge_para_with_text(
block,
formula_enable=formula_enable,
@@ -358,7 +355,7 @@ def mk_blocks_to_markdown(para_blocks: list[Block], make_mode: str, formula_enab
para_text += f"{item_text} \n"
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
- para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
+ para_text = f"{'#' * title_level} {merge_para_with_text(para_block)}"
elif para_type == BlockType.IMAGE:
if make_mode == MakeMode.NLP_MD:
continue
@@ -394,7 +391,7 @@ def mk_blocks_to_markdown(para_blocks: list[Block], make_mode: str, formula_enab
table_enable=table_enable,
)
- if para_text.strip() == '':
+ if para_text.strip() == "":
continue
else:
# page_markdown.append(para_text.strip() + ' ')
@@ -404,7 +401,7 @@ def mk_blocks_to_markdown(para_blocks: list[Block], make_mode: str, formula_enab
def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]) -> dict:
- para_type = para_block['type']
+ para_type = para_block.type
para_content = {}
if para_type in [
BlockType.TEXT,
@@ -417,110 +414,109 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
BlockType.PAGE_FOOTNOTE,
]:
para_content = {
- 'type': para_type,
- 'text': merge_para_with_text(para_block),
+ "type": para_type,
+ "text": merge_para_with_text(para_block),
}
elif para_type == BlockType.LIST:
para_content = {
- 'type': para_type,
- 'sub_type': para_block.get('sub_type', ''),
- 'list_items':[],
+ "type": para_type,
+ "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)
+ para_content["list_items"].append(item_text)
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
para_content = {
- 'type': ContentType.TEXT,
- 'text': merge_para_with_text(para_block),
+ "type": ContentType.TEXT,
+ "text": merge_para_with_text(para_block),
}
if title_level != 0:
- para_content['text_level'] = title_level
+ para_content["text_level"] = title_level
elif para_type == BlockType.INTERLINE_EQUATION:
para_content = {
- 'type': ContentType.EQUATION,
- 'text': merge_para_with_text(para_block),
- 'text_format': 'latex',
+ "type": ContentType.EQUATION,
+ "text": merge_para_with_text(para_block),
+ "text_format": "latex",
}
elif para_type == BlockType.IMAGE:
- para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
+ para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
image_path, image_content = get_body_data(para_block)
- para_content['img_path'] = _build_media_path(img_buket_path, image_path)
- para_content['content'] = image_content if image_content else ''
+ 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:
-
- if span.get('html', ''):
+ 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:
+ if span.get("html", ""):
para_content[BlockType.TABLE_BODY] = _format_embedded_html(
- span['html'],
+ span["html"],
img_buket_path,
)
- if span.get('image_path', ''):
- para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
+ 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)
para_content = {
- 'type': ContentType.CHART,
- 'img_path': _build_media_path(img_buket_path, image_path),
- 'content': chart_content if chart_content else '',
+ "type": ContentType.CHART,
+ "img_path": _build_media_path(img_buket_path, image_path),
+ "content": chart_content if chart_content else "",
BlockType.CHART_CAPTION: [],
BlockType.CHART_FOOTNOTE: [],
}
_apply_visual_sub_type(para_content, 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:
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 = {'type': BlockType.CODE, 'sub_type': para_block["sub_type"], BlockType.CODE_CAPTION: []}
- for block in para_block['blocks']:
- if block['type'] == BlockType.CODE_BODY:
+ 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:
+ 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
- para_bbox = para_block.get('bbox')
+ para_bbox = para_block.get("bbox")
if para_bbox:
x0, y0, x1, y1 = para_bbox
- para_content['bbox'] = [
+ para_content["bbox"] = [
int(x0 * 1000 / page_width),
int(y0 * 1000 / page_height),
int(x1 * 1000 / page_width),
int(y1 * 1000 / page_height),
]
- para_content['page_idx'] = page_idx
+ para_content["page_idx"] = page_idx
return para_content
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,
@@ -542,68 +538,62 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
else:
raise ValueError(f"Unknown para_type: {para_type}")
para_content = {
- 'type': content_type,
- 'content': {
+ "type": content_type,
+ "content": {
f"{content_type}_content": merge_para_with_text_v2(para_block),
- }
+ },
}
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
if title_level != 0:
para_content = {
- 'type': ContentTypeV2.TITLE,
- 'content': {
- "title_content": merge_para_with_text_v2(para_block),
- "level": title_level
- }
+ "type": ContentTypeV2.TITLE,
+ "content": {"title_content": merge_para_with_text_v2(para_block), "level": title_level},
}
else:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
"paragraph_content": merge_para_with_text_v2(para_block),
- }
+ },
}
- elif para_type in [
- BlockType.TEXT,
- BlockType.PHONETIC
- ]:
+ elif para_type in [BlockType.TEXT, BlockType.PHONETIC]:
para_content = {
- 'type': ContentTypeV2.PARAGRAPH,
- 'content': {
- 'paragraph_content': merge_para_with_text_v2(para_block),
- }
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
+ "paragraph_content": merge_para_with_text_v2(para_block),
+ },
}
elif para_type == BlockType.INTERLINE_EQUATION:
image_path, math_content = get_body_data(para_block)
para_content = {
- 'type': ContentTypeV2.EQUATION_INTERLINE,
- 'content': {
- 'math_content': math_content,
- 'math_type': 'latex',
- 'image_source': {'path': f"{img_buket_path}/{image_path}"},
- }
+ "type": ContentTypeV2.EQUATION_INTERLINE,
+ "content": {
+ "math_content": math_content,
+ "math_type": "latex",
+ "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ },
}
elif para_type == BlockType.IMAGE:
image_caption = []
image_footnote = []
image_path, image_content = get_body_data(para_block)
image_source = {
- 'path': _build_media_path(img_buket_path, image_path),
+ "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,
- 'content': {
- 'image_source': image_source,
- 'content': image_content if image_content else '',
- 'image_caption': image_caption,
- 'image_footnote': image_footnote,
- }
+ "type": ContentTypeV2.IMAGE,
+ "content": {
+ "image_source": image_source,
+ "content": image_content if image_content else "",
+ "image_caption": image_caption,
+ "image_footnote": image_footnote,
+ },
}
_apply_visual_sub_type(para_content, para_block)
elif para_type == BlockType.TABLE:
@@ -612,130 +602,128 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
image_path, html = get_body_data(para_block)
table_html = _format_embedded_html(html, img_buket_path)
image_source = {
- 'path': f"{img_buket_path}/{image_path}",
+ "path": f"{img_buket_path}/{image_path}",
}
if table_html.count("<table") > 1:
table_nest_level = 2
else:
table_nest_level = 1
- if (
- "colspan" in table_html or
- "rowspan" in table_html or
- table_nest_level > 1
- ):
+ if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
table_type = ContentTypeV2.TABLE_COMPLEX
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,
- 'content': {
- 'image_source': image_source,
- 'table_caption': table_caption,
- 'table_footnote': table_footnote,
- 'html': table_html,
- 'table_type': table_type,
- 'table_nest_level': table_nest_level,
- }
+ "type": ContentTypeV2.TABLE,
+ "content": {
+ "image_source": image_source,
+ "table_caption": table_caption,
+ "table_footnote": table_footnote,
+ "html": table_html,
+ "table_type": table_type,
+ "table_nest_level": table_nest_level,
+ },
}
elif para_type == BlockType.CHART:
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,
- 'content': {
- 'image_source': {
- 'path': _build_media_path(img_buket_path, image_path),
+ "type": ContentTypeV2.CHART,
+ "content": {
+ "image_source": {
+ "path": _build_media_path(img_buket_path, image_path),
},
- 'content': chart_content if chart_content else '',
- 'chart_caption': chart_caption,
- 'chart_footnote': chart_footnote,
- }
+ "content": chart_content if chart_content else "",
+ "chart_caption": chart_caption,
+ "chart_footnote": chart_footnote,
+ },
}
_apply_visual_sub_type(para_content, para_block)
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:
para_content = {
- 'type': ContentTypeV2.CODE,
- 'content': {
- 'code_caption': code_caption,
- 'code_content': code_content,
- 'code_language': para_block.get('guess_lang', 'txt'),
- }
+ "type": ContentTypeV2.CODE,
+ "content": {
+ "code_caption": code_caption,
+ "code_content": code_content,
+ "code_language": para_block.get("guess_lang", "txt"),
+ },
}
elif sub_type == BlockType.ALGORITHM:
para_content = {
- 'type': ContentTypeV2.ALGORITHM,
- 'content': {
- 'algorithm_caption': code_caption,
- 'algorithm_content': code_content,
- }
+ "type": ContentTypeV2.ALGORITHM,
+ "content": {
+ "algorithm_caption": code_caption,
+ "algorithm_content": code_content,
+ },
}
else:
raise ValueError(f"Unknown code sub_type: {sub_type}")
elif para_type == BlockType.REF_TEXT:
para_content = {
- 'type': ContentTypeV2.LIST,
- 'content': {
- 'list_type': ContentTypeV2.LIST_REF,
- 'list_items': [
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": ContentTypeV2.LIST_REF,
+ "list_items": [
{
- 'item_type': 'text',
- 'item_content': merge_para_with_text_v2(para_block),
+ "item_type": "text",
+ "item_content": merge_para_with_text_v2(para_block),
}
],
- }
+ },
}
elif para_type == BlockType.LIST:
- if 'sub_type' in para_block:
- if para_block['sub_type'] == BlockType.REF_TEXT:
+ if "sub_type" in para_block:
+ 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']}")
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({
- 'item_type': 'text',
- 'item_content': item_content,
- })
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
para_content = {
- 'type': ContentTypeV2.LIST,
- 'content': {
- 'list_type': list_type,
- 'list_items': list_items,
- }
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": list_type,
+ "list_items": list_items,
+ },
}
page_width, page_height = page_size
- para_bbox = para_block.get('bbox')
+ para_bbox = para_block.get("bbox")
if para_bbox:
x0, y0, x1, y1 = para_bbox
- para_content['bbox'] = [
+ para_content["bbox"] = [
int(x0 * 1000 / page_width),
int(y0 * 1000 / page_height),
int(x1 * 1000 / page_width),
@@ -745,9 +733,6 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
return para_content
-
-
-
def get_body_data(para_block: Block) -> tuple[str, str]:
"""
Extract image_path and body content from para_block
@@ -759,51 +744,51 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
- Default: ('', '')
"""
- def get_data_from_spans(lines):
+ def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
for line in lines:
- for span in line.get('spans', []):
- span_type = span.get('type')
+ for span in line.spans:
+ span_type = span.get("type")
if span_type == ContentType.TABLE:
- return span.get('image_path', ''), span.get('html', '')
+ return span.get("image_path", ""), span.get("html", "")
elif span_type == ContentType.CHART:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
elif span_type == ContentType.IMAGE:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
elif span_type == ContentType.INTERLINE_EQUATION:
- return span.get('image_path', ''), span.get('content', '')
+ return span.get("image_path", ""), span.get("content", "")
elif span_type == ContentType.TEXT:
- return '', span.get('content', '')
- return '', ''
+ return "", span.get("content", "")
+ return "", ""
# 处理嵌套的 blocks 结构
- if 'blocks' in para_block:
- for block in para_block['blocks']:
- block_type = block.get('type')
+ if para_block.blocks:
+ for block in para_block.blocks:
+ block_type = block.type
if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:
- result = get_data_from_spans(block.get('lines', []))
- if result != ('', ''):
+ result = get_data_from_spans(block.lines)
+ if result != ("", ""):
return result
- return '', ''
+ return "", ""
# 处理直接包含 lines 的结构
- return get_data_from_spans(para_block.get('lines', []))
+ return get_data_from_spans(para_block.lines)
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'))
- block_text += span['content']
+ 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"))
+ 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']
- if span.get("content", '').strip():
+ 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:
span_type = ContentTypeV2.SPAN_PHONETIC
@@ -815,49 +800,46 @@ def merge_para_with_text_v2(para_block: Block) -> str:
ContentTypeV2.SPAN_TEXT,
]:
# 定义CJK语言集合(中日韩)
- cjk_langs = {'zh', 'ja', 'ko'}
+ cjk_langs = {"zh", "ja", "ko"}
# 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: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
if has_following_joinable_span and not is_last_span:
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()
+ 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]
+ 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']} "
else:
- span_content = span['content']
+ span_content = span["content"]
- if para_content and para_content[-1]['type'] == span_type:
+ if para_content and para_content[-1]["type"] == span_type:
# 合并相同类型的span
- para_content[-1]['content'] += span_content
+ para_content[-1]["content"] += span_content
else:
span_content = {
- 'type': span_type,
- 'content': span_content,
+ "type": span_type,
+ "content": span_content,
}
para_content.append(span_content)
@@ -866,8 +848,8 @@ def merge_para_with_text_v2(para_block: Block) -> str:
ContentTypeV2.SPAN_EQUATION_INLINE,
]:
span_content = {
- 'type': span_type,
- 'content': span['content'],
+ "type": span_type,
+ "content": span["content"],
}
para_content.append(span_content)
else:
@@ -875,20 +857,21 @@ def merge_para_with_text_v2(para_block: Block) -> str:
return para_content
-def union_make(pdf_info_dict: list,
- make_mode: str,
- img_buket_path: str = '',
- ) -> str | list:
+def union_make(
+ pdf_info_dict: list,
+ 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')
+ 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")
output_content = []
for page_info in pdf_info_dict:
- paras_of_layout = page_info.get('para_blocks')
- paras_of_discarded = page_info.get('discarded_blocks')
- page_idx = page_info.get('page_idx')
- page_size = page_info.get('page_size')
+ paras_of_layout = page_info.get("para_blocks")
+ paras_of_discarded = page_info.get("discarded_blocks")
+ page_idx = page_info.get("page_idx")
+ page_size = page_info.get("page_size")
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
if not paras_of_layout:
continue
@@ -912,14 +895,14 @@ def union_make(pdf_info_dict: list,
output_content.append(page_contents)
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
- return '\n\n'.join(output_content)
+ return "\n\n".join(output_content)
elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:
return output_content
return None
def get_title_level(block: Block) -> int:
- title_level = block.get('level', 1)
+ title_level = block.get("level", 1)
if title_level > 4:
title_level = 4
elif title_level < 1:
diff --git a/mineru/types.py b/mineru/types.py
index a7dac799..08e71c0f 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -2,7 +2,302 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import Any, Iterator
+from enum import Enum
+from typing import Any, Iterator, Literal
+
+
+class BlockType:
+ IMAGE = "image"
+ TABLE = "table"
+ CHART = "chart"
+ IMAGE_BODY = "image_body"
+ TABLE_BODY = "table_body"
+ CHART_BODY = "chart_body"
+ CAPTION = "caption" # generic caption type (e.g., for Word documents)
+ IMAGE_CAPTION = "image_caption"
+ TABLE_CAPTION = "table_caption"
+ CHART_CAPTION = "chart_caption"
+ ALGORITHM_CAPTION = "algorithm_caption"
+ FOOTNOTE = "footnote" # pp_layout中的vision_footnote
+ IMAGE_FOOTNOTE = "image_footnote"
+ TABLE_FOOTNOTE = "table_footnote"
+ CHART_FOOTNOTE = "chart_footnote"
+ TEXT = "text"
+ TITLE = "title"
+ INTERLINE_EQUATION = "interline_equation"
+ EQUATION = "equation" # 公式(独立公式)
+ LIST = "list"
+ INDEX = "index"
+ DISCARDED = "discarded"
+
+ # Added in vlm 2.5
+ CODE = "code"
+ CODE_BODY = "code_body"
+ CODE_CAPTION = "code_caption"
+ CODE_FOOTNOTE = "code_footnote"
+ ALGORITHM = "algorithm"
+ REF_TEXT = "ref_text"
+ PHONETIC = "phonetic"
+ HEADER = "header"
+ FOOTER = "footer"
+ PAGE_NUMBER = "page_number"
+ ASIDE_TEXT = "aside_text"
+ PAGE_FOOTNOTE = "page_footnote"
+
+ # Added in pp_doclayout_v2
+ ABSTRACT = "abstract"
+ DOC_TITLE = "doc_title"
+ PARAGRAPH_TITLE = "paragraph_title"
+ VERTICAL_TEXT = "vertical_text"
+ HEADER_IMAGE = "header_image"
+ FOOTER_IMAGE = "footer_image"
+ FORMULA_NUMBER = "formula_number"
+
+
+class ContentType:
+ IMAGE = "image"
+ TABLE = "table"
+ CHART = "chart"
+ TEXT = "text"
+ INTERLINE_EQUATION = "interline_equation"
+ INLINE_EQUATION = "inline_equation"
+ EQUATION = "equation"
+ HYPERLINK = "hyperlink"
+
+
+class ContentTypeV2:
+ CODE = "code"
+ ALGORITHM = "algorithm"
+ EQUATION_INTERLINE = "equation_interline"
+ IMAGE = "image"
+ TABLE = "table"
+ CHART = "chart"
+ TABLE_SIMPLE = "simple_table"
+ TABLE_COMPLEX = "complex_table"
+ LIST = "list"
+ LIST_TEXT = "text_list"
+ LIST_REF = "reference_list"
+ INDEX = "index"
+ TITLE = "title"
+ PARAGRAPH = "paragraph"
+ SPAN_TEXT = "text"
+ SPAN_EQUATION_INLINE = "equation_inline"
+ SPAN_PHONETIC = "phonetic"
+ SPAN_MD = "md"
+ SPAN_CODE_INLINE = "code_inline"
+ PAGE_HEADER = "page_header"
+ PAGE_FOOTER = "page_footer"
+ PAGE_NUMBER = "page_number"
+ PAGE_ASIDE_TEXT = "page_aside_text"
+ PAGE_FOOTNOTE = "page_footnote"
+
+
+BlockTypes = Literal[
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.IMAGE_BODY,
+ BlockType.TABLE_BODY,
+ BlockType.CHART_BODY,
+ BlockType.CAPTION,
+ BlockType.IMAGE_CAPTION,
+ BlockType.TABLE_CAPTION,
+ BlockType.CHART_CAPTION,
+ BlockType.ALGORITHM_CAPTION,
+ BlockType.FOOTNOTE,
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.TEXT,
+ BlockType.TITLE,
+ BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
+ BlockType.LIST,
+ BlockType.INDEX,
+ BlockType.DISCARDED,
+ BlockType.CODE,
+ BlockType.CODE_BODY,
+ BlockType.CODE_CAPTION,
+ BlockType.CODE_FOOTNOTE,
+ BlockType.ALGORITHM,
+ BlockType.REF_TEXT,
+ BlockType.PHONETIC,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+ BlockType.ABSTRACT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.VERTICAL_TEXT,
+ BlockType.HEADER_IMAGE,
+ BlockType.FOOTER_IMAGE,
+ BlockType.FORMULA_NUMBER,
+]
+
+BLOCK_TYPES = {
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.IMAGE_BODY,
+ BlockType.TABLE_BODY,
+ BlockType.CHART_BODY,
+ BlockType.CAPTION,
+ BlockType.IMAGE_CAPTION,
+ BlockType.TABLE_CAPTION,
+ BlockType.CHART_CAPTION,
+ BlockType.ALGORITHM_CAPTION,
+ BlockType.FOOTNOTE,
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.TEXT,
+ BlockType.TITLE,
+ BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
+ BlockType.LIST,
+ BlockType.INDEX,
+ BlockType.DISCARDED,
+ BlockType.CODE,
+ BlockType.CODE_BODY,
+ BlockType.CODE_CAPTION,
+ BlockType.CODE_FOOTNOTE,
+ BlockType.ALGORITHM,
+ BlockType.REF_TEXT,
+ BlockType.PHONETIC,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+ BlockType.ABSTRACT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.VERTICAL_TEXT,
+ BlockType.HEADER_IMAGE,
+ BlockType.FOOTER_IMAGE,
+ BlockType.FORMULA_NUMBER,
+}
+
+# NOT_EXTRACT_TYPES = {
+# BlockType.TEXT,
+# BlockType.TITLE,
+# BlockType.HEADER,
+# BlockType.FOOTER,
+# BlockType.PAGE_NUMBER,
+# BlockType.PAGE_FOOTNOTE,
+# BlockType.REF_TEXT,
+# BlockType.TABLE_CAPTION,
+# BlockType.IMAGE_CAPTION,
+# BlockType.TABLE_FOOTNOTE,
+# BlockType.IMAGE_FOOTNOTE,
+# BlockType.CODE_CAPTION,
+# BlockType.PHONETIC,
+# }
+# HYBRID_OCR_DET_TEXT_TYPES = NOT_EXTRACT_TYPES
+#
+#
+# class NotExtractType(Enum):
+# TEXT = BlockType.TEXT
+# TITLE = BlockType.TITLE
+# HEADER = BlockType.HEADER
+# FOOTER = BlockType.FOOTER
+# PAGE_NUMBER = BlockType.PAGE_NUMBER
+# PAGE_FOOTNOTE = BlockType.PAGE_FOOTNOTE
+# REF_TEXT = BlockType.REF_TEXT
+# TABLE_CAPTION = BlockType.TABLE_CAPTION
+# IMAGE_CAPTION = BlockType.IMAGE_CAPTION
+# TABLE_FOOTNOTE = BlockType.TABLE_FOOTNOTE
+# IMAGE_FOOTNOTE = BlockType.IMAGE_FOOTNOTE
+# CODE_CAPTION = BlockType.CODE_CAPTION
+# PHONETIC = BlockType.PHONETIC
+#
+#
+# not_extract_list = [item.value for item in NotExtractType] + [
+# BlockType.CAPTION,
+# BlockType.FOOTNOTE,
+# 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,
+# BlockType.ABSTRACT,
+# BlockType.ASIDE_TEXT,
+# BlockType.PHONETIC,
+# BlockType.CHART_CAPTION,
+# BlockType.CHART_FOOTNOTE,
+# BlockType.CODE_FOOTNOTE,
+# }
+
+
+# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。
+TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {
+ BlockType.TEXT,
+ BlockType.REF_TEXT,
+ BlockType.ABSTRACT,
+ BlockType.PHONETIC,
+}
+
+# layout.pdf 中这些 block 直接使用自身 bbox,复合 block 则使用子 block bbox。
+DIRECT_LAYOUT_BBOX_BLOCK_TYPES = TEXT_LIKE_BLOCK_TYPES_FOR_BBOX | {
+ BlockType.TITLE,
+ BlockType.INTERLINE_EQUATION,
+ BlockType.LIST,
+ BlockType.INDEX,
+}
+
+# span.pdf 从这些结构性 block 中收集内部 span bbox。
+SPAN_SOURCE_BLOCK_TYPES = DIRECT_LAYOUT_BBOX_BLOCK_TYPES
+
+
+IMAGE_BLOCK_BODY = "image_block_body"
+GENERIC_CHILD_TYPES = (BlockType.CAPTION, BlockType.FOOTNOTE)
+INLINE_CAPTION_FRAGMENT_TYPES = {BlockType.TEXT, BlockType.FOOTNOTE}
+STACKED_TABLE_CAPTION_CLUSTER_TYPES = {
+ BlockType.CAPTION,
+ BlockType.TEXT,
+ BlockType.FOOTNOTE,
+}
+VISUAL_RELATION_IGNORED_TYPES = {
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.PAGE_FOOTNOTE,
+ BlockType.ASIDE_TEXT,
+}
+VISUAL_MAIN_TYPES = {
+ BlockType.IMAGE_BODY: BlockType.IMAGE,
+ IMAGE_BLOCK_BODY: BlockType.IMAGE,
+ BlockType.TABLE_BODY: BlockType.TABLE,
+ BlockType.CHART_BODY: BlockType.CHART,
+ BlockType.CODE_BODY: BlockType.CODE,
+}
+VISUAL_TYPE_MAPPING = {
+ BlockType.IMAGE: {
+ "body": BlockType.IMAGE_BODY,
+ "caption": BlockType.IMAGE_CAPTION,
+ "footnote": BlockType.IMAGE_FOOTNOTE,
+ },
+ BlockType.TABLE: {
+ "body": BlockType.TABLE_BODY,
+ "caption": BlockType.TABLE_CAPTION,
+ "footnote": BlockType.TABLE_FOOTNOTE,
+ },
+ BlockType.CHART: {
+ "body": BlockType.CHART_BODY,
+ "caption": BlockType.CHART_CAPTION,
+ "footnote": BlockType.CHART_FOOTNOTE,
+ },
+ BlockType.CODE: {
+ "body": BlockType.CODE_BODY,
+ "caption": BlockType.CODE_CAPTION,
+ "footnote": BlockType.CODE_FOOTNOTE,
+ },
+}
+
# ── dict-compatibility for dataclass-backed model objects ──────────
#
@@ -68,8 +363,6 @@ def _install_dict_compat(*classes) -> None:
cls.__contains__ = _extra_contains
-
-
# ── model types ─────────────────────────────────────────────────────
@@ -107,6 +400,7 @@ class Line:
"""A line within a block, containing one or more spans."""
spans: list[Span] = field(default_factory=list)
+ bbox: tuple[float, float, float, float] | None = None
_extra: dict = field(default_factory=dict)
@classmethod
@@ -127,6 +421,8 @@ class Block:
sub_type: str = ""
html: str = ""
merge_prev: bool = False
+ index: int | None = None
+ guess_lang: str = ""
_extra: dict = field(default_factory=dict)
@classmethod
@@ -142,6 +438,8 @@ class Block:
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", ""),
)
def all_spans(self) -> Iterator[Span]:
diff --git a/mineru/utils/pdf_reader.py b/mineru/utils/pdf_reader.py
index c6a715e6..1d9d6569 100644
--- a/mineru/utils/pdf_reader.py
+++ b/mineru/utils/pdf_reader.py
@@ -5,19 +5,20 @@ from io import BytesIO
from loguru import logger
from PIL import Image
from pypdfium2 import PdfBitmap, PdfPage
-from mineru.utils.pdfium_guard import pdfium_guard
+
+from .pdfium_guard import pdfium_guard
def page_to_image(
page: PdfPage,
dpi: int = 200,
max_width_or_height: int = 3500, # changed from 4500 to 3500
-) -> (Image.Image, float):
+) -> tuple[Image.Image, float]:
with pdfium_guard():
scale = dpi / 72
long_side_length = max(*page.get_size())
- if (long_side_length*scale) > max_width_or_height:
+ if (long_side_length * scale) > max_width_or_height:
scale = max_width_or_height / long_side_length
bitmap: PdfBitmap | None = None
diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.py
index 97918f29..b3f83ea1 100644
--- a/mineru/utils/pdfium_guard.py
+++ b/mineru/utils/pdfium_guard.py
@@ -1,13 +1,12 @@
# Copyright (c) Opendatalab. All rights reserved.
import threading
-from io import BytesIO
from contextlib import contextmanager
-from typing import Any, Callable, Sequence, TypeVar
+from io import BytesIO
+from typing import Any, Callable, Iterator, Sequence, TypeVar
from loguru import logger
-from mineru.utils.pdf_page_id import get_end_page_id
-
+from .pdf_page_id import get_end_page_id
_pdfium_lock = threading.RLock()
@@ -15,7 +14,7 @@ T = TypeVar("T")
@contextmanager
-def pdfium_guard():
+def pdfium_guard() -> Iterator[None]:
with _pdfium_lock:
yield
@@ -124,19 +123,13 @@ def rewrite_pdf_bytes_with_pdfium(
if page_indices is not None:
normalized_page_indices = sorted(
- {
- page_index
- for page_index in page_indices
- if 0 <= page_index < total_page_count
- }
+ {page_index for page_index in page_indices if 0 <= page_index < total_page_count}
)
if not normalized_page_indices:
return b""
else:
normalized_end_page_id = get_end_page_id(end_page_id, total_page_count)
- normalized_page_indices = list(
- range(start_page_id, normalized_end_page_id + 1)
- )
+ normalized_page_indices = list(range(start_page_id, normalized_end_page_id + 1))
output_doc = pdfium.PdfDocument.new()
output_doc.import_pages(pdf_doc, normalized_page_indices)
diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.py
index f0263eb4..344725d0 100644
--- a/mineru/utils/title_level_postprocess.py
+++ b/mineru/utils/title_level_postprocess.py
@@ -10,18 +10,13 @@ from loguru import logger
from mineru.utils.config_reader import get_llm_aided_config
from mineru.utils.llm_aided import llm_aided_title
-
SUPPORTED_PDF_BACKENDS = {"pipeline", "vlm", "hybrid"}
def _resolve_title_aided_config() -> dict[str, Any] | None:
"""从本地配置解析标题分级开关。"""
llm_aided_config = get_llm_aided_config()
- title_aided_config = (
- llm_aided_config.get("title_aided")
- if isinstance(llm_aided_config, dict)
- else None
- )
+ title_aided_config = llm_aided_config.get("title_aided") if isinstance(llm_aided_config, dict) else None
if not isinstance(title_aided_config, dict) or not title_aided_config:
return None
if not title_aided_config.get("enable", False):
@@ -68,7 +63,7 @@ def finalize_client_side_middle_json(middle_json: dict[str, Any]) -> dict[str, A
pdf_info,
)
elif backend == "hybrid":
- from mineru.backend.hybrid.hybrid_model_output_to_middle_json import (
+ from mineru.backend.hybrid.model_output_to_middle_json import (
finalize_middle_json_from_preproc,
)