Skip to content

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

refactor: introduce BBox/IntBBox type aliases, unify bbox types across codebase

jinzhenj2f91679052ff
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index e5c9fb2c..21ae94a7 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -5,14 +5,14 @@ import asyncio
import os
import time
from collections import defaultdict
-from typing import Any
+from typing import Any, Literal
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, ExtractResult
+from mineru_vl_utils.structs import BlockType
from PIL import Image
from tqdm import tqdm
@@ -88,7 +88,7 @@ def ocr_classify(
return _ocr_enable
-def ocr_det(
+def _ocr_det(
hybrid_pipeline_model: Any,
np_images: list[Any],
model_list: list[list[dict[str, Any]]],
@@ -97,7 +97,7 @@ def ocr_det(
batch_ratio: int = 1,
*,
fill_text: bool = True,
-) -> None:
+) -> list[list[dict[str, Any]]]:
def _set_temp_pixel_bbox(res: dict[str, Any], pixel_bbox: list[int]) -> None:
res["_normalized_bbox"] = list(res["bbox"])
res["bbox"] = pixel_bbox
@@ -107,7 +107,8 @@ def ocr_det(
if normalized_bbox is not None:
res["bbox"] = normalized_bbox
- ocr_res_list = []
+ ocr_res_list: list[list[dict[str, Any]]] = []
+
if not hybrid_pipeline_model.enable_ocr_det_batch:
# 非批处理模式 - 逐页处理
for np_image, page_mfd_res, page_results in tqdm(
@@ -130,7 +131,7 @@ def ocr_det(
finally:
_restore_normalized_bbox(res)
adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(page_mfd_res, useful_list)
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
ocr_res = run_ocr_det_inference(
hybrid_pipeline_model.ocr_model.ocr,
bgr_image,
@@ -170,7 +171,7 @@ def ocr_det(
finally:
_restore_normalized_bbox(res)
adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(page_mfd_res, useful_list)
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
all_cropped_images_info.append((bgr_image, useful_list, adjusted_mfdetrec_res, ocr_res_list[-1]))
# 按分辨率分组并同时完成padding
@@ -187,7 +188,7 @@ def ocr_det(
resolution_groups[group_key].append(crop_info)
# 对每个分辨率组进行批处理
- for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det"):
+ for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc="OCR-det"):
# 对所有图像进行padding到统一尺寸
batch_images = []
for crop_info in group_crops:
@@ -235,7 +236,7 @@ def ocr_det(
return ocr_res_list
-def mask_image_regions(np_images: list[Any], model_list: list[list[dict[str, Any]]]) -> list[Any]:
+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]
@@ -307,7 +308,7 @@ def _build_inline_formula_inputs(images_layout_res: list[list[dict[str, Any]]])
return inline_formula_inputs
-def _build_formula_mask_inputs(images_layout_res: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
+def _build_formula_mask_inputs(images_layout_res: list[list[dict[str, Any]]]) -> list[list[dict[str, Any]]]:
"""从 layout 检测结果提取公式框,供 OCR det 规避行内/行间公式区域。"""
page_formula_masks = []
for layout_res in images_layout_res:
@@ -331,7 +332,7 @@ def _normalize_page_size(page_image: Any) -> tuple[int, int]:
return width, height
-def _bbox_to_pixel_bbox(bbox: BBox, page_size: list[int]) -> BBox | None:
+def _bbox_to_pixel_bbox(bbox: BBox | None, page_size: tuple[int, int]) -> BBox | None:
"""将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""
if bbox is None or len(bbox) != 4:
return None
@@ -352,7 +353,7 @@ def _bbox_to_pixel_bbox(bbox: BBox, page_size: list[int]) -> BBox | None:
return (left, top, right, bottom)
-def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: list[int]) -> list[BBox]:
+def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: tuple[int, int]) -> list[BBox]:
"""只收集layout小模型输出的doc_title框,忽略paragraph_title等其他类型。"""
doc_title_bboxes: list[BBox] = []
for layout_item in layout_res or []:
@@ -375,7 +376,7 @@ def _has_doc_title_overlap(title_bbox: BBox, doc_title_bboxes: list[BBox], overl
def _apply_layout_title_split(
model_list: list[list[dict[str, Any]]],
images_layout_res: list[list[dict[str, Any]]],
- page_sizes: list[list[int]],
+ page_sizes: list[tuple[int, int]],
overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,
) -> None:
"""用layout doc_title框将VLM title拆分为doc_title和paragraph_title。"""
@@ -395,20 +396,20 @@ def _apply_layout_title_split(
def _predict_layout_for_title_split(
hybrid_pipeline_model: MineruHybridModel,
- images: list[Image.Image],
+ np_images: list[np.ndarray] | list[Image.Image],
batch_ratio: int,
) -> list[list[dict[str, Any]]]:
"""执行layout小模型检测,专门为Hybrid标题拆分提供页面layout结果。"""
return run_layout_inference(
hybrid_pipeline_model.layout_model.batch_predict,
- images,
+ np_images,
batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE),
)
def _process_ocr_and_formulas(
images_pil_list: list[Image.Image],
- model_list: list[ExtractResult],
+ model_list: list[list[dict[str, Any]]],
language: str | None,
inline_formula_enable: bool,
_ocr_enable: bool,
@@ -431,12 +432,8 @@ def _process_ocr_and_formulas(
)
# 在进行`行内`公式检测和识别前,先将图像中的图片、表格、`行间`公式区域mask掉
- layout_images = mask_image_regions(np_images, model_list) if inline_formula_enable else np_images
- images_layout_res = _predict_layout_for_title_split(
- hybrid_pipeline_model,
- layout_images,
- batch_ratio,
- )
+ layout_images = _mask_image_regions(np_images, model_list) if inline_formula_enable else np_images
+ images_layout_res = _predict_layout_for_title_split(hybrid_pipeline_model, layout_images, batch_ratio)
if inline_formula_enable:
images_mfd_res = _build_inline_formula_inputs(images_layout_res)
@@ -462,7 +459,7 @@ def _process_ocr_and_formulas(
mfd_res.append(page_mfd_res)
# vlm没有执行ocr,需要ocr_det
- ocr_res_list = ocr_det(
+ ocr_res_list = _ocr_det(
hybrid_pipeline_model,
np_images,
model_list,
@@ -571,7 +568,7 @@ def _process_ocr_and_formulas(
def _apply_layout_title_split_for_window(
images_pil_list: list[Image.Image],
- model_list: list[ExtractResult],
+ model_list: list[list[dict[str, Any]]],
language: str | None,
batch_ratio: int,
) -> MineruHybridModel:
@@ -587,7 +584,7 @@ def _apply_layout_title_split_for_window(
batch_ratio,
)
np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
- ocr_res_list = ocr_det(
+ ocr_res_list = _ocr_det(
hybrid_pipeline_model,
np_images,
model_list,
@@ -653,9 +650,9 @@ def _merge_page_sidecar_items(
ocr_res_list: list[list[dict[str, Any]]],
keep_ocr_text: bool = True,
) -> list[list[dict[str, Any]]]:
- merged_model_list = []
+ merged_model_list: list[list[dict[str, Any]]] = []
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)
+ merged_page_model_list: list[dict[str, Any]] = list(page_model_list)
merged_page_model_list.extend(
_build_inline_formula_model_item(formula) for formula in page_inline_formula_list if formula.get("bbox") is not None
)
@@ -738,7 +735,14 @@ def doc_analyze(
pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend: str = "transformers",
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ] = "transformers",
parse_method: str = "auto",
language: str = "ch",
inline_formula_enable: bool = True,
@@ -758,7 +762,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: list[ExtractResult] = []
+ model_list: list[list[dict[str, Any]]] = []
doc_closed = False
hybrid_pipeline_model = None
try:
@@ -882,7 +886,14 @@ async def aio_doc_analyze(
pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend: str = "transformers",
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ] = "transformers",
parse_method: str = "auto",
language: str = "ch",
inline_formula_enable: bool = True,
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index ec995806..928d4081 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -8,7 +8,7 @@ from typing import Any
from loguru import logger
from PIL import Image
-from ...types import BBox, Block, IntBBox, Line, Span
+from ...types import EMPTY_BBOX, BBox, Block, IntBBox, Line, Span
from ...utils.enum_class import BlockType, ContentType, NotExtractType
from ...utils.guess_suffix_or_lang import guess_language_by_text
from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
@@ -74,8 +74,8 @@ class MagicModel:
blocks: list[Block] = []
self.all_spans: list[Span] = []
+ page_text_inline_formula_spans: list[Span] = []
- page_text_inline_formula_spans = []
for inline_formula in self.page_inline_formula:
inline_formula["bbox"] = list(self.cal_real_bbox(inline_formula["bbox"]))
inline_formula_latex = inline_formula.pop("latex", "")
@@ -181,7 +181,7 @@ class MagicModel:
span = None
if span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:
span = Span(type=span_type, bbox=block_bbox)
- if span_type == ContentType.TABLE:
+ if span_type == ContentType.TABLE and block_content is not None:
span.html = block_content
elif raw_block_type in ["image", "chart"] and block_content is not None:
span.content = block_content
@@ -189,7 +189,7 @@ class MagicModel:
span = Span(
type=span_type,
bbox=block_bbox,
- content=isolated_formula_clean(block_content),
+ content=isolated_formula_clean(block_content or ""),
)
elif _vlm_ocr_enable or block_type not in not_extract_list:
# vlm_ocr_enable 模式下,所有文本块都直接使用 block 的内容
@@ -250,7 +250,7 @@ class MagicModel:
span = Span(
type=span_type,
bbox=block_bbox,
- content=block_content,
+ content=block_content or "",
)
if span_type in [
@@ -399,8 +399,13 @@ class MagicModel:
if not block_spans:
return []
- hint_block = {"spans": copy.deepcopy(block_spans)}
- return fix_text_block(hint_block)["lines"]
+ fix_block = Block(
+ index=0,
+ type="",
+ bbox=EMPTY_BBOX,
+ _fix_spans=copy.deepcopy(block_spans),
+ )
+ return fix_text_block(fix_block).lines
def cal_real_bbox(self, bbox: BBox) -> IntBBox:
x1, y1, x2, y2 = bbox
@@ -493,7 +498,7 @@ def fix_list_blocks(
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"
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index ce4e8a9a..6abd1b45 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -46,7 +46,7 @@ def blocks_to_page_info(
page_model_list: list[dict[str, Any]],
image_dict: dict[str, Any],
page: Any,
- image_writer: DataWriter,
+ image_writer: DataWriter | None,
page_index: int,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
@@ -115,7 +115,7 @@ def blocks_to_page_info(
page_info = PageInfo(
preproc_blocks=page_blocks,
discarded_blocks=discarded_blocks,
- page_size=[width, height],
+ page_size=(width, height),
page_idx=page_index,
)
return page_info
diff --git a/mineru/backend/office/docx_analyze.py b/mineru/backend/office/docx_analyze.py
index 7c3950c5..5d744cd5 100644
--- a/mineru/backend/office/docx_analyze.py
+++ b/mineru/backend/office/docx_analyze.py
@@ -10,7 +10,7 @@ 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[str, Any]:
+def office_docx_analyze(file_bytes: bytes, image_writer: Any = None) -> tuple[dict[str, Any], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
diff --git a/mineru/backend/office/mkcontent/inline_renderer.py b/mineru/backend/office/mkcontent/inline_renderer.py
index d7a8742f..3b50bb9f 100644
--- a/mineru/backend/office/mkcontent/inline_renderer.py
+++ b/mineru/backend/office/mkcontent/inline_renderer.py
@@ -141,7 +141,9 @@ def _escape_office_inline_text(content: str, inline_syntax: str) -> str:
def get_title_level(para_block: Block) -> int:
- title_level = para_block.get("level", 2)
+ title_level = para_block.level
+ if title_level is None:
+ title_level = 2
return title_level
@@ -483,18 +485,18 @@ def _iter_para_inline_spans(para_block: Block) -> Generator[Span, None, None]:
def _hyperlink_requires_html(span: Span) -> bool:
"""判断 hyperlink 是否存在混合或复杂样式,需要整块切到 HTML。"""
- children = span.get("children") or []
+ children = span._children
if not children:
- return not _is_simple_markdown_style(span.get("style", []))
+ return not _is_simple_markdown_style(span._style)
child_style_keys = set()
for child in children:
- if child.get("type") != ContentType.TEXT:
+ if child.type != ContentType.TEXT:
return True
- content = str(child.get("content", ""))
+ content = child.content
if not content.strip():
continue
- child_style = child.get("style", [])
+ child_style = child._style
child_style_key = _get_markdown_style_key(child_style)
if child_style_key == "":
return True
@@ -506,8 +508,8 @@ def _hyperlink_requires_html(span: Span) -> bool:
def _iter_block_inline_units(para_block: Block) -> Generator[dict[str, Any], None, None]:
"""把 block 展开为线性文本单元,用于判断 Markdown 边界风险。"""
if para_block.type == BlockType.TITLE:
- section_number = para_block.get("section_number", "")
- if para_block.get("is_numbered_style", False) and section_number:
+ section_number = para_block.section_number
+ if para_block.is_numbered_style and section_number:
yield {
"span_type": ContentType.TEXT,
"content": f"{section_number} ",
@@ -520,24 +522,24 @@ def _iter_block_inline_units(para_block: Block) -> Generator[dict[str, Any], Non
yield {
"span_type": ContentType.TEXT,
"content": span.content,
- "style": span.get("style", []),
+ "style": span._style,
}
elif span_type == ContentType.HYPERLINK:
- children = span.get("children") or []
+ children = span._children
if children:
for child in children:
- if child.get("type") != ContentType.TEXT:
+ if child.type != ContentType.TEXT:
continue
yield {
"span_type": ContentType.HYPERLINK,
- "content": str(child.get("content", "")),
- "style": child.get("style", []),
+ "content": str(child.content),
+ "style": child._style,
}
else:
yield {
"span_type": ContentType.HYPERLINK,
"content": span.content,
- "style": span.get("style", []),
+ "style": span._style,
}
elif span_type in {ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}:
yield {
@@ -815,19 +817,14 @@ def _append_style_grouped_text_parts(
)
-def _render_hyperlink_children_label(children: list[dict], inline_syntax: str) -> str:
+def _render_hyperlink_children_label(children: list[Span], inline_syntax: str) -> str:
"""渲染 hyperlink 的子文本片段,保留各自样式后再组成同一个链接 label。"""
child_parts = []
child_text_spans = []
for child in children or []:
- if child.get("type") != ContentType.TEXT:
+ if child.type != ContentType.TEXT:
continue
- child_text_spans.append(
- {
- "content": child.get("content", ""),
- "style": child.get("style", []),
- }
- )
+ child_text_spans.append({"content": child.content, "style": child._style})
_append_style_grouped_text_parts(child_parts, child_text_spans, inline_syntax)
return _join_rendered_parts(child_parts).strip()
@@ -839,7 +836,7 @@ def _append_hyperlink_part(
inline_syntax: str,
url: str = "",
plain_text_only: bool = False,
- children: list[dict[str, Any]] | None = None,
+ children: list[Span] | None = None,
) -> None:
"""渲染 hyperlink 片段;HTML block 使用 <a>,Markdown block 使用 []()。"""
if children:
@@ -886,8 +883,8 @@ def merge_para_with_text(para_block: Block, escape_text_block_prefix: bool = Tru
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.is_numbered_style:
+ section_number = para_block.section_number
if section_number:
parts.append(
_make_rendered_part(
@@ -899,7 +896,7 @@ def merge_para_with_text(para_block: Block, escape_text_block_prefix: bool = Tru
for line in para_block.lines:
for span in line.spans:
span_type = span.type
- span_style = span.get("style", [])
+ span_style = span._style
if span_type == ContentType.TEXT:
text_span_buffer.append(
@@ -937,8 +934,8 @@ def merge_para_with_text(para_block: Block, escape_text_block_prefix: bool = Tru
span.content,
span_style,
inline_syntax,
- url=span.get("url", ""),
- children=span.get("children"),
+ url=span._url,
+ children=span._children,
)
else:
flush_text_span_buffer()
diff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/backend/office/mkcontent/output_builders.py
index e63f870c..4eb9613b 100644
--- a/mineru/backend/office/mkcontent/output_builders.py
+++ b/mineru/backend/office/mkcontent/output_builders.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
from collections.abc import Generator
+from dataclasses import asdict
from typing import Any
from ....types import Block, Line, Span
@@ -23,13 +24,13 @@ from .inline_renderer import (
)
-def _prefix_table_img_src(html: str, img_buket_path: str) -> str:
+def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:
"""给表格 HTML 内的本地图片 src 加上输出图片目录前缀。"""
- if not html or not img_buket_path:
+ if not html or not img_bucket_path:
return html
return re.sub(
r'src="(?!data:)([^"]+)"',
- lambda m: f'src="{img_buket_path}/{m.group(1)}"',
+ lambda m: f'src="{img_bucket_path}/{m.group(1)}"',
html,
)
@@ -46,24 +47,27 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
)
-def _format_embedded_html(html: str, img_buket_path: str) -> str:
+def _format_embedded_html(html: str, img_bucket_path: str) -> str:
"""统一处理 Office 嵌入 HTML 的图片路径和行内公式标签。"""
- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))
+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))
-def _build_media_path(img_buket_path: str, image_path: str) -> str:
+def _build_media_path(img_bucket_path: str, image_path: str) -> str:
"""构造图片展示路径,空图片路径保持为空。"""
if not image_path:
return ""
- if not img_buket_path:
+ if not img_bucket_path:
return image_path
- return f"{img_buket_path}/{image_path}"
+ return f"{img_bucket_path}/{image_path}"
def _get_ordered_list_start(list_block: Block) -> int:
"""读取有序列表起始编号,兼容旧版数据缺少 start 字段的情况。"""
try:
- return int(list_block.get("start", 1))
+ start = list_block.start
+ if start is None:
+ start = 1
+ return int(start)
except (TypeError, ValueError):
return 1
@@ -71,7 +75,10 @@ def _get_ordered_list_start(list_block: Block) -> int:
def _get_list_ilevel(list_block: Block) -> int:
"""安全读取 DOCX 列表原始 ilevel,异常值按顶层 0 处理。"""
try:
- return int(list_block.get("ilevel", 0))
+ ilevel = list_block.ilevel
+ if ilevel is None:
+ ilevel = 0
+ return int(ilevel)
except (TypeError, ValueError):
return 0
@@ -87,12 +94,12 @@ def _flatten_list_items(list_block: Block, root_ilevel: int | None = None) -> li
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._list_attribute or "unordered"
indent = " " * relative_ilevel
ordered_counter = _get_ordered_list_start(list_block)
for block in list_block.blocks:
- if block["type"] in [BlockType.LIST, BlockType.INDEX]:
+ 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)
@@ -112,11 +119,11 @@ def _flatten_list_items_v2(list_block: Block, root_ilevel: int | None = None) ->
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._list_attribute or "unordered"
ordered_counter = _get_ordered_list_start(list_block)
for block in list_block.blocks:
- if block["type"] in [BlockType.LIST, BlockType.INDEX]:
+ 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)
@@ -132,7 +139,7 @@ def _flatten_list_items_v2(list_block: Block, root_ilevel: int | None = None) ->
"prefix": prefix,
"item_content": item_content,
}
- anchor = block.get("anchor")
+ anchor = block.anchor
if isinstance(anchor, str) and anchor.strip():
item["anchor"] = anchor.strip()
items.append(item)
@@ -150,19 +157,13 @@ def _collect_index_span_items(text_block: Block) -> list[tuple[str, str, list[st
span_items = []
for line in text_block.lines:
for span in line.spans:
- span_items.append(
- (
- span.get("content", ""),
- span.get("type"),
- span.get("style", []),
- )
- )
+ span_items.append((span.content, span.type, span._style))
return span_items
def _normalize_anchor(block: Block) -> str | None:
"""规范化 block 锚点,空值返回 None。"""
- anchor = block.get("anchor")
+ anchor = block.anchor
if not isinstance(anchor, str) or not anchor.strip():
return None
return anchor.strip()
@@ -302,11 +303,14 @@ def _render_index_leaf_item(text_block: Block, indent: str) -> str | None:
def _flatten_index_items(index_block: Block) -> list[str]:
"""递归展平目录 block,保留目录锚点和目录项样式。"""
items = []
- indent = " " * index_block.get("ilevel", 0)
+ ilevel = index_block.ilevel
+ if ilevel is None:
+ ilevel = 0
+ indent = " " * ilevel
for child in index_block.blocks:
- if child.get("type") == BlockType.INDEX:
+ if child.type == BlockType.INDEX:
items.extend(_flatten_index_items(child))
- elif child.get("type") == BlockType.TEXT:
+ elif child.type == BlockType.TEXT:
item_text = _render_index_leaf_item(child, indent)
if item_text:
items.append(item_text)
@@ -321,7 +325,7 @@ def merge_index_to_markdown(index_block: Block) -> str:
def _iter_child_blocks(para_block: Block, block_type: str) -> Generator[Block, None, None]:
"""按原始顺序遍历指定类型的子 block。"""
for block in para_block.blocks:
- if block.get("type") == block_type:
+ if block.type == block_type:
yield block
@@ -336,7 +340,7 @@ def _iter_body_spans(para_block: Block, body_type: str, span_type: str) -> Gener
"""遍历视觉类 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.type == span_type:
yield span
@@ -354,16 +358,16 @@ def _collect_caption_v2(para_block: Block, caption_type: str) -> list[dict[str,
def mk_blocks_to_markdown(
- para_blocks: list[Block], make_mode: MakeMode, img_buket_path: str = "", page_idx: int | None = None
-) -> str:
+ para_blocks: list[Block], make_mode: MakeMode, img_bucket_path: str = "", page_idx: int | None = None
+) -> list[str]:
page_markdown = []
for para_block in para_blocks:
para_text = ""
- para_type = para_block["type"]
+ 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")
+ bookmark_anchor = para_block.anchor
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:
@@ -373,7 +377,7 @@ def mk_blocks_to_markdown(
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
title_text = merge_para_with_text(para_block)
- bookmark_anchor = para_block.get("anchor")
+ bookmark_anchor = para_block.anchor
if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():
para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'
else:
@@ -387,8 +391,8 @@ def mk_blocks_to_markdown(
BlockType.IMAGE_BODY,
ContentType.IMAGE,
):
- if span.get("image_path", ""):
- para_text += f"![]({img_buket_path}/{span['image_path']})"
+ if span:
+ para_text += f"![]({img_bucket_path}/{span.image_path})"
for caption_text in _collect_caption_texts(
para_block,
BlockType.IMAGE_CAPTION,
@@ -404,7 +408,7 @@ def mk_blocks_to_markdown(
BlockType.TABLE_BODY,
ContentType.TABLE,
):
- para_text += f"\n{_format_embedded_html(span['html'], img_buket_path)}\n"
+ para_text += f"\n{_format_embedded_html(span.html, img_bucket_path)}\n"
for caption_text in _collect_caption_texts(
para_block,
BlockType.TABLE_CAPTION,
@@ -416,9 +420,9 @@ def mk_blocks_to_markdown(
elif make_mode == MakeMode.MM_MD:
image_path, chart_content = get_body_data(para_block)
if chart_content:
- para_text += f"\n{_format_embedded_html(chart_content, img_buket_path)}\n"
+ para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"
elif image_path:
- para_text += f"![]({_build_media_path(img_buket_path, image_path)})"
+ para_text += f"![]({_build_media_path(img_bucket_path, image_path)})"
else:
continue
for caption_text in _collect_caption_texts(
@@ -435,9 +439,9 @@ def mk_blocks_to_markdown(
return page_markdown
-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 = {}
+def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_idx: int | None) -> dict[str, Any]:
+ para_type = para_block.type
+ para_content: dict[str, Any] = {}
if para_type in [
BlockType.TEXT,
BlockType.HEADER,
@@ -479,8 +483,8 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
BlockType.IMAGE_BODY,
ContentType.IMAGE,
):
- if span.get("image_path", ""):
- para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ if span.image_path:
+ para_content["img_path"] = f"{img_bucket_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: []}
@@ -489,11 +493,8 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
BlockType.TABLE_BODY,
ContentType.TABLE,
):
- if span.get("html", ""):
- para_content[BlockType.TABLE_BODY] = _format_embedded_html(
- span["html"],
- img_buket_path,
- )
+ if span.html:
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)
para_content[BlockType.TABLE_CAPTION].extend(_collect_caption_texts(para_block, BlockType.TABLE_CAPTION))
elif para_type == BlockType.CHART:
para_content = {
@@ -502,33 +503,23 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
"content": "",
BlockType.CHART_CAPTION: [],
}
- for span in _iter_body_spans(
- para_block,
- BlockType.CHART_BODY,
- ContentType.CHART,
- ):
- para_content["img_path"] = _build_media_path(
- img_buket_path,
- span.get("image_path", ""),
- )
- if span.get("content", ""):
- para_content["content"] = _format_embedded_html(
- span["content"],
- img_buket_path,
- )
+ for span in _iter_body_spans(para_block, BlockType.CHART_BODY, ContentType.CHART):
+ para_content["img_path"] = _build_media_path(img_bucket_path, span.image_path)
+ if span.content:
+ para_content["content"] = _format_embedded_html(span.content, img_bucket_path)
para_content[BlockType.CHART_CAPTION].extend(_collect_caption_texts(para_block, BlockType.CHART_CAPTION))
para_content["page_idx"] = page_idx
- anchor = para_block.get("anchor")
+ anchor = para_block.anchor
if isinstance(anchor, str) and anchor.strip():
para_content["anchor"] = anchor.strip()
return para_content
-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 = {}
+def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+ para_type = para_block.type
+ para_content: dict[str, Any] = {}
if para_type in [
BlockType.HEADER,
BlockType.FOOTER,
@@ -583,7 +574,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> li
elif para_type == BlockType.IMAGE:
image_path, _ = get_body_data(para_block)
image_source = {
- "path": f"{img_buket_path}/{image_path}",
+ "path": f"{img_bucket_path}/{image_path}",
}
para_content = {
"type": ContentTypeV2.IMAGE,
@@ -613,7 +604,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> li
para_block,
BlockType.TABLE_CAPTION,
),
- "html": _format_embedded_html(html, img_buket_path),
+ "html": _format_embedded_html(html, img_bucket_path),
"table_type": table_type,
"table_nest_level": table_nest_level,
},
@@ -624,9 +615,9 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> li
"type": ContentTypeV2.CHART,
"content": {
"image_source": {
- "path": _build_media_path(img_buket_path, image_path),
+ "path": _build_media_path(img_bucket_path, image_path),
},
- "content": _format_embedded_html(chart_content, img_buket_path),
+ "content": _format_embedded_html(chart_content, img_bucket_path),
"chart_caption": _collect_caption_v2(
para_block,
BlockType.CHART_CAPTION,
@@ -635,7 +626,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> li
}
elif para_type == BlockType.LIST:
list_type = ContentTypeV2.LIST_TEXT
- attribute = para_block.get("attribute", "unordered")
+ attribute = para_block._list_attribute or "unordered"
para_content = {
"type": ContentTypeV2.LIST,
"content": {
@@ -653,7 +644,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str) -> li
},
}
- anchor = para_block.get("anchor")
+ anchor = para_block.anchor
if isinstance(anchor, str) and anchor.strip():
para_content["anchor"] = anchor.strip()
@@ -671,25 +662,25 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
"""
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")
- if span_type == ContentType.TABLE:
- return span.get("image_path", ""), span.get("html", "")
- elif span_type == ContentType.CHART:
- return span.get("image_path", ""), span.get("content", "")
- elif span_type == ContentType.IMAGE:
- return span.get("image_path", ""), ""
- elif span_type == ContentType.INTERLINE_EQUATION:
- return span.get("image_path", ""), span.get("content", "")
- elif span_type == ContentType.TEXT:
- return "", span.get("content", "")
+ for line in lines:
+ for span in line.spans:
+ span_type = span.type
+ if span_type == ContentType.TABLE:
+ return span.image_path, span.html
+ elif span_type == ContentType.CHART:
+ return span.image_path, span.content
+ elif span_type == ContentType.IMAGE:
+ return span.image_path, ""
+ elif span_type == ContentType.INTERLINE_EQUATION:
+ return span.image_path, span.content
+ elif span_type == ContentType.TEXT:
+ return "", span.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.lines)
if result != ("", ""):
@@ -704,15 +695,15 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
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.content
+ span_style = span._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._children:
+ child_content = child.content
+ child_style = child._style
if child_content.strip():
return True
if child_content and child_style and any(s in visible_styles for s in child_style):
@@ -720,12 +711,12 @@ def _span_has_content_for_v2(span: Span, visible_styles: set[str]) -> bool:
return False
-def merge_para_with_text_v2(para_block: Block) -> str:
+def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
"""将 Office 段落转换为 content_list_v2 spans,避免原地修改 middle_json。"""
_visible_styles = {"underline", "strikethrough"}
- para_content = []
- if para_block.get("type") == BlockType.TITLE:
- section_number = para_block.get("section_number", "")
+ para_content: list[dict[str, Any]] = []
+ if para_block.type == BlockType.TITLE:
+ section_number = para_block.section_number
if section_number:
# v2 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。
para_content.append(
@@ -734,10 +725,10 @@ def merge_para_with_text_v2(para_block: Block) -> str:
"content": f"{section_number} ",
}
)
- for line in para_block["lines"]:
- for span in line["spans"]:
+ for line in para_block.lines:
+ for span in line.spans:
if _span_has_content_for_v2(span, _visible_styles):
- rendered_span = dict(span)
+ rendered_span = asdict(span)
if rendered_span["type"] == ContentType.INLINE_EQUATION:
rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINE
para_content.append(rendered_span)
@@ -747,9 +738,8 @@ def merge_para_with_text_v2(para_block: Block) -> str:
def union_make(
pdf_info_dict: list[dict[str, Any]],
make_mode: MakeMode,
- img_buket_path: str = "",
+ img_bucket_path: str = "",
) -> list[str] | None:
-
output_content = []
for page_info in pdf_info_dict:
paras_of_layout = page_info.get("para_blocks")
@@ -758,14 +748,14 @@ def union_make(
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_bucket_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 [])
if not para_blocks:
continue
for para_block in para_blocks:
- para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx)
+ para_content = make_blocks_to_content_list(para_block, img_bucket_path, page_idx)
output_content.append(para_content)
elif make_mode == MakeMode.CONTENT_LIST_V2:
# https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md
@@ -773,7 +763,7 @@ def union_make(
page_contents = []
if para_blocks:
for para_block in para_blocks:
- para_content = make_blocks_to_content_list_v2(para_block, img_buket_path)
+ para_content = make_blocks_to_content_list_v2(para_block, img_bucket_path)
page_contents.append(para_content)
output_content.append(page_contents)
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index cbe97b47..c621322c 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -50,24 +50,22 @@ def blocks_to_page_info(page_blocks: list[dict[str, Any]], image_writer: Any, pa
text_blocks = magic_model.get_text_blocks()
interline_equation_blocks = magic_model.get_interline_equation_blocks()
- page_blocks = []
- page_blocks.extend(
- [
- *image_blocks,
- *chart_blocks,
- *table_blocks,
- *title_blocks,
- *text_blocks,
- *interline_equation_blocks,
- *list_blocks,
- *index_blocks,
- ]
- )
+ blocks = [
+ *image_blocks,
+ *chart_blocks,
+ *table_blocks,
+ *title_blocks,
+ *text_blocks,
+ *interline_equation_blocks,
+ *list_blocks,
+ *index_blocks,
+ ]
+
# 对page_blocks根据index的值进行排序
- page_blocks.sort(key=lambda x: x["index"])
+ blocks.sort(key=lambda x: x.index)
page_info = PageInfo(
- para_blocks=page_blocks,
+ para_blocks=blocks,
discarded_blocks=discarded_blocks,
page_idx=page_index,
)
@@ -121,15 +119,15 @@ def _link_index_entries_by_anchor(middle_json: dict[str, Any]) -> None:
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")
+ anchor = text_block.anchor
if not isinstance(anchor, str):
- text_block.pop("anchor", None)
+ text_block.anchor = ""
continue
anchor = anchor.strip()
if not anchor or anchor not in valid_anchors:
- text_block.pop("anchor", None)
+ text_block.anchor = ""
continue
- text_block["anchor"] = anchor
+ text_block.anchor = anchor
def result_to_middle_json(model_output_blocks_list: list[list[dict[str, Any]]], image_writer: object) -> dict[str, Any]:
@@ -155,7 +153,7 @@ def result_to_middle_json(model_output_blocks_list: list[list[dict[str, Any]]],
if deeper > level:
section_counters[deeper] = 0
# Build section number string, e.g. "1.2.1"
- section_number = ".".join(str(section_counters[l]) for l in range(1, level + 1))
+ section_number = ".".join(str(section_counters[lvl]) for lvl in range(1, level + 1))
block["section_number"] = section_number
else:
# Some documents embed the section number directly in the content
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 5958d4e0..4de6f3bb 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -86,9 +86,9 @@ class MagicModel:
and anchor.strip()
and block_type in [BlockType.TITLE, BlockType.TEXT, BlockType.INTERLINE_EQUATION]
):
- block["anchor"] = anchor.strip()
+ block.anchor = anchor.strip()
if block_type == BlockType.TITLE:
- block["is_numbered_style"] = block_info.get("is_numbered_style", False)
+ block.is_numbered_style = block_info.get("is_numbered_style", False)
block.level = block_info.get("level", 1)
blocks.append(block)
@@ -114,10 +114,10 @@ class MagicModel:
self.text_blocks.append(block)
elif block.type == BlockType.TITLE:
self.title_blocks.append(block)
- elif block.type in [BlockType.REF_TEXT]:
- self.ref_text_blocks.append(block)
- elif block.type in [BlockType.PHONETIC]:
- self.phonetic_blocks.append(block)
+ # elif block.type in [BlockType.REF_TEXT]:
+ # 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,
@@ -138,7 +138,7 @@ class MagicModel:
self.chart_blocks, not_include_chart_blocks = fix_two_layer_blocks(self.chart_blocks, BlockType.CHART)
for block in not_include_image_blocks + not_include_table_blocks + not_include_chart_blocks:
- block["type"] = BlockType.TEXT
+ block.type = BlockType.TEXT
self.text_blocks.append(block)
def get_list_blocks(self) -> list[Block]:
@@ -176,14 +176,14 @@ def _parse_style_list(style_str: str | None) -> list[str]:
return [style.strip() for style in style_str.split(",") if style.strip()]
-def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re: re.Pattern[str]) -> tuple[str, list[Span], str]:
+def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re: re.Pattern[str]) -> tuple[list[Span], str]:
"""解析一个 hyperlink 内部的多个 text 子片段,并保留每段样式。"""
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 [], ""
- children = []
+ children: list[Span] = []
pos = 0
while pos < url_start:
text_match = text_tag_re.search(hyperlink_content, pos)
@@ -194,13 +194,12 @@ def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re: re.Patte
if text_end == -1 or text_end > url_start:
return [], ""
- child = {
- "type": ContentType.TEXT,
- "content": hyperlink_content[text_match.end() : text_end],
- }
- style = _parse_style_list(text_match.group(1))
- if style:
- child["style"] = style
+ child = Span(
+ type=ContentType.TEXT,
+ bbox=EMPTY_BBOX,
+ content=hyperlink_content[text_match.end() : text_end],
+ _style=_parse_style_list(text_match.group(1)),
+ )
children.append(child)
pos = text_end + 7
@@ -293,7 +292,7 @@ def parse_text_block_spans(content: str) -> list[Span]:
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, bbox=EMPTY_BBOX, 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
@@ -321,19 +320,18 @@ def parse_text_block_spans(content: str) -> list[Span]:
span = Span(
type=ContentType.HYPERLINK,
bbox=EMPTY_BBOX,
- content=child["content"],
+ content=child.content,
+ _url=link_url,
+ _style=child._style,
)
- span["url"] = link_url
- if child.get("style"):
- span["style"] = child["style"]
else:
span = Span(
type=ContentType.HYPERLINK,
bbox=EMPTY_BBOX,
- content="".join(child["content"] for child in children),
+ content="".join(child.content for child in children),
+ _url=link_url,
+ _children=children,
)
- span["url"] = link_url
- span["children"] = children
spans.append(span)
pos = hyperlink_end + 12
last_end = pos
@@ -382,12 +380,15 @@ def parse_list_block(list_block: dict[str, Any]) -> Block | None:
blocks.append(nested_list)
# 构建当前列表block
- result = Block(type=BlockType.LIST, bbox=EMPTY_BBOX, index=0, blocks=blocks)
- result["attribute"] = list_block.get("attribute", "unordered")
- result["ilevel"] = list_block.get("ilevel", 0)
- if "start" in list_block:
- result["start"] = list_block["start"]
-
+ result = Block(
+ type=BlockType.LIST,
+ bbox=EMPTY_BBOX,
+ index=0,
+ blocks=blocks,
+ start=list_block.get("start"),
+ ilevel=list_block.get("ilevel", 0),
+ _list_attribute=list_block.get("attribute", "unordered"),
+ )
return result
@@ -416,7 +417,7 @@ def parse_index_block(index_block: dict[str, Any]) -> Block | None:
text_block = Block(type=BlockType.TEXT, bbox=EMPTY_BBOX, index=0, lines=[Line(bbox=EMPTY_BBOX, spans=spans)])
anchor = item.get("anchor")
if isinstance(anchor, str) and anchor.strip():
- text_block["anchor"] = anchor.strip()
+ text_block.anchor = anchor.strip()
blocks.append(text_block)
elif item_type == "index":
@@ -424,9 +425,13 @@ def parse_index_block(index_block: dict[str, Any]) -> Block | None:
if nested_index:
blocks.append(nested_index)
- result = Block(type=BlockType.INDEX, bbox=EMPTY_BBOX, index=0, blocks=blocks)
- result["ilevel"] = index_block.get("ilevel", 0)
-
+ result = Block(
+ type=BlockType.INDEX,
+ bbox=EMPTY_BBOX,
+ index=0,
+ blocks=blocks,
+ ilevel=index_block.get("ilevel", 0),
+ )
return result
@@ -601,7 +606,7 @@ def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, obj
def get_type_blocks(blocks: list[Block], block_type: Literal["image", "table", "chart"]) -> list[dict[str, Any]]:
with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")
- ret = []
+ ret: list[dict[str, Any]] = []
for v in with_captions:
record = {
f"{block_type}_body": v["sub_bbox"],
@@ -611,11 +616,14 @@ def get_type_blocks(blocks: list[Block], block_type: Literal["image", "table", "
return ret
-def fix_two_layer_blocks(blocks: list[Block], fix_type: Literal["image", "table", "chart"]) -> list[Block]:
+def fix_two_layer_blocks(blocks: list[Block], fix_type: Literal["image", "table", "chart"]) -> tuple[list[Block], list[Block]]:
+ """TODO: this function has many unknown types."""
+
need_fix_blocks = get_type_blocks(blocks, fix_type)
- fixed_blocks = []
- not_include_blocks = []
- processed_indices = set()
+
+ fixed_blocks: list[Block] = []
+ not_include_blocks: list[Block] = []
+ processed_indices: set[int] = set()
# 将每个block的caption_list中不连续index的元素提出来作为普通block处理
for block in need_fix_blocks:
@@ -660,21 +668,18 @@ def fix_two_layer_blocks(blocks: list[Block], fix_type: Literal["image", "table"
processed_indices.add(body["index"])
- two_layer_block = {
- "type": fix_type,
- "blocks": [body],
- "index": body["index"],
- }
- two_layer_block["blocks"].extend([*caption_list])
- # 对blocks按index排序
- two_layer_block["blocks"].sort(key=lambda x: x["index"])
-
+ two_layer_block = Block(
+ index=body["index"],
+ type=fix_type,
+ bbox=EMPTY_BBOX,
+ blocks=sorted([body, *caption_list], key=lambda x: x.index),
+ )
fixed_blocks.append(two_layer_block)
# 添加未处理的blocks
for block in blocks:
- block.pop("type", None)
- if block["index"] not in processed_indices and block not in not_include_blocks:
+ block.type = ""
+ if block.index not in processed_indices and block not in not_include_blocks:
not_include_blocks.append(block)
return fixed_blocks, not_include_blocks
diff --git a/mineru/backend/office/pptx_analyze.py b/mineru/backend/office/pptx_analyze.py
index 2f580757..53dfd7e2 100644
--- a/mineru/backend/office/pptx_analyze.py
+++ b/mineru/backend/office/pptx_analyze.py
@@ -12,7 +12,7 @@ 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[str, Any]:
+def office_pptx_analyze(file_bytes: bytes, image_writer: Any = None) -> tuple[dict[str, Any], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
diff --git a/mineru/backend/office/xlsx_analyze.py b/mineru/backend/office/xlsx_analyze.py
index 155deaf8..af527dd1 100644
--- a/mineru/backend/office/xlsx_analyze.py
+++ b/mineru/backend/office/xlsx_analyze.py
@@ -12,7 +12,7 @@ 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[str, Any]:
+def office_xlsx_analyze(file_bytes: bytes, image_writer: Any = None) -> tuple[dict[str, Any], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
index 418e4b07..9ebb6194 100644
--- a/mineru/backend/pipeline/batch_analyze.py
+++ b/mineru/backend/pipeline/batch_analyze.py
@@ -590,7 +590,8 @@ class BatchAnalyze:
# 单独拿出有线表格进行预测
wired_table_res_list = []
for table_res_dict in table_res_list_all_page:
- # logger.debug(f"Table classification result: {table_res_dict["table_res"]["cls_label"]} with confidence {table_res_dict["table_res"]["cls_score"]}")
+ # logger.debug(f"Table classification result: {table_res_dict["table_res"]["cls_label"]}
+ # with confidence {table_res_dict["table_res"]["cls_score"]}")
if (
table_res_dict["table_res"]["cls_label"] == AtomicModel.WirelessTable
and table_res_dict["table_res"]["cls_score"] < 0.9
@@ -640,7 +641,7 @@ class BatchAnalyze:
)
# BGR转换
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
det_image = self._get_masked_det_image(
bgr_image,
adjusted_mfdetrec_res,
@@ -753,7 +754,7 @@ class BatchAnalyze:
ocr_res_list_dict["single_page_mfdetrec_res"], useful_list
)
# OCR-det
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
det_image = self._get_masked_det_image(
bgr_image,
adjusted_mfdetrec_res,
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 7bca00b2..3820b504 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -22,7 +22,7 @@ def blocks_to_page_info(
page_model_info: dict[str, Any],
image_dict: dict[str, Any],
page: Any,
- image_writer: DataWriter,
+ image_writer: DataWriter | None,
page_index: int,
ocr_enable: bool = False,
) -> PageInfo:
@@ -31,6 +31,7 @@ def blocks_to_page_info(
page_img_md5 = bytes_md5(page_pil_img.tobytes())
with pdfium_guard():
page_w, page_h = map(int, page.get_size())
+
magic_model = MagicModel(page_model_info, page, scale, page_pil_img, page_w, page_h, ocr_enable)
"""从magic_model对象中获取后面会用到的区块信息"""
@@ -46,16 +47,13 @@ def blocks_to_page_info(
"""构造page_info"""
replace_inline_table_images(preproc_blocks, image_writer, page_index)
- page_info = make_page_info_dict(
- preproc_blocks,
- page_index,
- page_w,
- page_h,
- discarded_blocks,
+ return PageInfo(
+ preproc_blocks=preproc_blocks,
+ page_idx=page_index,
+ page_size=(page_w, page_h),
+ discarded_blocks=discarded_blocks,
)
- return page_info
-
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}
@@ -211,7 +209,7 @@ def init_middle_json() -> dict[str, Any]:
def result_to_middle_json(
- model_list: list[list[dict[str, Any]]],
+ model_list: list[dict[str, Any]],
images_list: list[dict[str, Any]],
pdf_doc: Any,
image_writer: DataWriter,
@@ -230,12 +228,3 @@ def result_to_middle_json(
lang=lang,
ocr_enable=ocr_enable,
)
-
-
-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,
- page_size=[page_w, page_h],
- discarded_blocks=discarded_blocks,
- )
diff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.py
index 6c53cb84..2e6b94ed 100644
--- a/mineru/backend/pipeline/para_split.py
+++ b/mineru/backend/pipeline/para_split.py
@@ -11,27 +11,27 @@ LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":
LIST_END_FLAG = (".", "。", ";", ";")
-def __process_blocks(blocks: list[Block]) -> list[Block]:
+def __process_blocks(blocks: list[Block]) -> list[list[Block]]:
# 对所有block预处理
# 1.通过title和interline_equation将block分组
# 2.bbox边界根据line信息重置
- result = []
- current_group = []
+ result: list[list[Block]] = []
+ current_group: list[Block] = []
for i in range(len(blocks)):
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)
+ current_block._bbox_fs = copy.deepcopy(current_block.bbox)
if current_block.lines:
- current_block["bbox_fs"] = [
+ 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)
# 检查下一个块是否存在
@@ -70,11 +70,14 @@ def __is_list_or_index_block(block: Block) -> str:
# 一个block如果是index block 应该同时满足以下特征
# 1.block内有多个line 2.block 内有多个line两侧均顶格写 3.line的开头或者结尾均为数字
if len(block.lines) >= 2:
+ assert block._bbox_fs is not None
+ assert block._page_size is not None
+
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"]
+ 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
@@ -94,9 +97,9 @@ def __is_list_or_index_block(block: Block) -> str:
# 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
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
@@ -118,23 +121,20 @@ def __is_list_or_index_block(block: Block) -> str:
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
- ):
+ 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:
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:
# 类中文没有超长单词的情况,可以用统一的阈值
@@ -147,7 +147,7 @@ def __is_list_or_index_block(block: Block) -> str:
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结尾
@@ -202,7 +202,7 @@ def __is_list_or_index_block(block: Block) -> str:
# 这种是每个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 abs(block._bbox_fs[0] - line.bbox[0]) < line_height / 2:
line._is_list_start = True
# 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
elif line_end_flag:
@@ -219,10 +219,11 @@ def __is_list_or_index_block(block: Block) -> str:
line._is_list_start = 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._is_list_end = True
line_start_flag = True
- # 一种有缩进的特殊有序list,start line 左侧不贴边且以数字开头,end line 以 IS_LIST_END_FLAG 结尾且数量和start line 一致
+ # 一种有缩进的特殊有序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):
if len(lines_text_list[i]) > 0:
@@ -233,9 +234,9 @@ def __is_list_or_index_block(block: Block) -> str:
else:
# 正常有缩进的list处理
for line in block.lines:
- if abs(block["bbox_fs"][0] - line.bbox[0]) < line_height / 2:
+ if abs(block._bbox_fs[0] - line.bbox[0]) < line_height / 2:
line._is_list_start = True
- if abs(block["bbox_fs"][2] - line.bbox[2]) > line_height:
+ if abs(block._bbox_fs[2] - line.bbox[2]) > line_height:
line._is_list_end = True
return BlockType.LIST
@@ -247,12 +248,15 @@ def __is_list_or_index_block(block: Block) -> str:
def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
if len(block1.lines) > 0 and len(block2.lines) > 0:
+ assert block1._bbox_fs is not None
+ assert block2._bbox_fs is not None
+
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:
+ 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]
@@ -264,7 +268,7 @@ def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
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)
# 两个block宽度差距超过2倍也不合并
@@ -278,7 +282,7 @@ def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
# 两个块任意一个块需要大于1行
and (len(block1.lines) > 1 or len(block2.lines) > 1)
):
- if block1["page_num"] != block2["page_num"]:
+ if block1._page_num != block2._page_num:
for line in block1.lines:
for span in line.spans:
span._cross_page = True
@@ -291,31 +295,34 @@ def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
if len(block1.lines) > 0 and len(block2.lines) > 0:
+ assert block1._bbox_fs is not None
+ assert block2._bbox_fs is not None
+
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:
+ 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", "")
+ first_content = first_span.content
+ last_content = last_span.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"]:
+ if block1._page_num != block2._page_num:
for line in block1.lines:
for span in line.spans:
span._cross_page = True
@@ -327,7 +334,7 @@ def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> tuple[Block,
def __merge_2_list_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
- if block1["page_num"] != block2["page_num"]:
+ if block1._page_num != block2._page_num:
for line in block1.lines:
for span in line.spans:
span._cross_page = True
@@ -349,8 +356,9 @@ def __is_list_group(text_blocks_group: list[Block]) -> bool:
return True
-def __para_merge_page(blocks: list[Block]) -> list[Block]:
+def __para_merge_page(blocks: list[Block]) -> None:
page_text_blocks_groups = __process_blocks(blocks)
+
for text_blocks_group in page_text_blocks_groups:
if len(text_blocks_group) > 0:
# 需要先在合并前对所有block判断是否为list or index block
@@ -385,26 +393,27 @@ def __para_merge_page(blocks: list[Block]) -> list[Block]:
def para_split(page_info_list: list[PageInfo]) -> None:
- all_blocks = []
+ all_blocks: list[Block] = []
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._page_num is not None:
+ if block._page_num == page_info.page_idx:
if block.type == BlockType.VERTICAL_TEXT:
block.type = BlockType.TEXT
- page_info["para_blocks"].append(block)
+ page_info.para_blocks.append(block)
# 从block中删除不需要的page_num和page_size字段
- del block["page_num"]
- del block["page_size"]
+ block._page_num = None
+ block._page_size = None
if __name__ == "__main__":
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index cd8d877e..e3dd0d52 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -323,7 +323,7 @@ def batch_image_analyze(
images_with_extra_info: list[tuple[Image.Image, bool, str]],
formula_enable: bool = True,
table_enable: bool = True,
-) -> object:
+) -> list[list[dict[str, Any]]]:
from .batch_analyze import BatchAnalyze
model_manager = ModelSingleton()
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 8530b0eb..0c4d35e1 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -53,8 +53,16 @@ class MagicModel:
"vision_footnote": BlockType.FOOTNOTE,
}
- VISUAL_MAIN_TYPES: tuple[str, ...] = (BlockType.IMAGE, BlockType.TABLE, BlockType.CHART, BlockType.CODE)
- VISUAL_CHILD_TYPES: tuple[str, ...] = (BlockType.CAPTION, BlockType.FOOTNOTE)
+ VISUAL_MAIN_TYPES: set[str] = {
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.CODE,
+ }
+ VISUAL_CHILD_TYPES: set[str] = {
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ }
VISUAL_TYPE_MAPPING: dict[str, dict[str, str]] = {
BlockType.IMAGE: {
"body": BlockType.IMAGE_BODY,
@@ -101,7 +109,8 @@ class MagicModel:
self.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spans
self.__post_process() # index重排,填充行内公式和文本span
if not ocr_enable:
- virtual_block = [0, 0, page_w, page_h, None, None, None, "text"]
+ # Bad code
+ virtual_block = (0, 0, page_w, page_h, None, None, None, "text")
self.page_ocr_res = txt_spans_extract(
page,
self.page_ocr_res,
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index cfb2f312..b69cd726 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import re
+from copy import deepcopy
from html import unescape
from typing import Any
@@ -15,7 +16,7 @@ from ..utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
from ..utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
-def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_buket_path: str = "") -> list[str]:
+def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_bucket_path: str = "") -> list[str]:
page_markdown = []
for para_block in paras_of_layout:
para_text = ""
@@ -28,25 +29,25 @@ def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_buket_p
elif para_type == BlockType.INTERLINE_EQUATION:
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].content:
para_text = merge_para_with_text(para_block)
else:
- para_text = f"![]({img_buket_path}/{para_block['lines'][0]['spans'][0]['image_path']})"
+ para_text = f"![]({img_bucket_path}/{para_block.lines[0].spans[0].image_path})"
elif para_type == BlockType.IMAGE:
if mode == MakeMode.NLP_MD:
continue
elif mode == MakeMode.MM_MD:
- para_text = merge_visual_blocks_to_markdown(para_block, img_buket_path)
+ para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)
elif para_type == BlockType.CHART:
if mode == MakeMode.NLP_MD:
continue
elif mode == MakeMode.MM_MD:
- para_text = merge_visual_blocks_to_markdown(para_block, img_buket_path)
+ para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)
elif para_type == BlockType.TABLE:
if mode == MakeMode.NLP_MD:
continue
elif mode == MakeMode.MM_MD:
- para_text = merge_visual_blocks_to_markdown(para_block, img_buket_path)
+ para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)
elif para_type == BlockType.CODE:
para_text = merge_visual_blocks_to_markdown(para_block)
@@ -58,7 +59,7 @@ def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_buket_p
return page_markdown
-def merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = "") -> str:
+def merge_visual_blocks_to_markdown(para_block: Block, img_bucket_path: str = "") -> str:
# 将 image/table/chart/code 这类视觉块的子 block 按阅读顺序拼接成 markdown。
# 这里不再写死 caption/body/footnote 的优先级,而是先展开成 segment,
# 再根据 markdown_line / html_block 两类片段决定分隔方式。
@@ -66,7 +67,7 @@ def merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = "")
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))
+ rendered_segments.extend(render_visual_block_segments(render_block, img_bucket_path, para_block))
para_text = ""
prev_segment_kind = None
@@ -86,12 +87,12 @@ def get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:
block
for _, block in sorted(
enumerate(blocks),
- key=lambda item: (item[1].get("index", float("inf")), item[0]),
+ key=lambda item: (item[1].index, item[0]),
)
]
-def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block | dict[str, Any]:
+def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block:
# pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。
# markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。
if block.type != BlockType.CODE_BODY:
@@ -99,21 +100,21 @@ def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> B
if parent_block.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 = not block.sub_type and parent_block.sub_type
+ needs_guess_lang = not block.guess_lang and parent_block.guess_lang
if not needs_sub_type and not needs_guess_lang:
return block
- render_block = dict(block)
+ render_block = deepcopy(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: Block, img_buket_path: str = "", para_block: Block | None = None
+ block: Block, img_bucket_path: str = "", para_block: Block | None = None
) -> list[tuple[str, str]]:
# 将单个视觉子 block 渲染成一个或多个 segment。
# 文本类子块统一输出 markdown_line;
@@ -142,16 +143,10 @@ def render_visual_block_segments(
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.image_path:
+ rendered_segments.append((f"![]({img_bucket_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.content, (para_block.sub_type if para_block else None) or "image content"
)
if details_block:
rendered_segments.append((details_block, "details_block"))
@@ -159,10 +154,10 @@ def render_visual_block_segments(
if block_type == BlockType.CHART_BODY:
return [
- (f"![]({img_buket_path}/{span['image_path']})", "markdown_line")
+ (f"![]({img_bucket_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 span.type == ContentType.CHART and span.image_path
]
if block_type == BlockType.TABLE_BODY:
@@ -171,15 +166,10 @@ def render_visual_block_segments(
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.html:
+ rendered_segments.append((_format_embedded_html(span.html, img_bucket_path), "html_block"))
+ elif span.image_path:
+ rendered_segments.append((f"![]({img_bucket_path}/{span.image_path})", "markdown_line"))
return rendered_segments
return []
@@ -215,14 +205,14 @@ inline_right_delimiter = delimiters["inline"]["right"]
CJK_LANGS = {"zh", "ja", "ko"}
-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:
+def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:
+ """Prefix non-data image sources in table HTML with img_bucket_path."""
+ if not html or not img_bucket_path:
return html
return re.sub(
r'src="(?!data:)([^"]+)"',
- lambda match: f'src="{img_buket_path}/{match.group(1)}"',
+ lambda match: f'src="{img_bucket_path}/{match.group(1)}"',
html,
)
@@ -240,9 +230,9 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
)
-def _format_embedded_html(html: str, img_buket_path: str) -> str:
+def _format_embedded_html(html: str, img_bucket_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))
+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))
def _normalize_visual_content(content: str) -> str:
@@ -263,7 +253,7 @@ def _build_visual_details_block(content: str, summary: str) -> str:
return f"<details>\n<summary>{summary}</summary>\n\n{normalized_content}\n</details>"
-def _apply_visual_sub_type(para_content: str, para_block: Block) -> str:
+def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
"""将视觉父块的 sub_type 透传到 content_list 输出顶层。"""
sub_type = para_block.sub_type
if sub_type:
@@ -272,15 +262,11 @@ def _apply_visual_sub_type(para_content: str, para_block: Block) -> str:
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",
- )
+ code_text = _merge_para_text(para_block, escape_markdown=False, 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"
+ guess_lang = para_block.guess_lang or "txt"
return f"```{guess_lang}\n{code_text}\n```"
para_text = _merge_para_text(para_block)
@@ -336,7 +322,7 @@ def _collect_text_for_lang_detection(para_block: Block) -> str:
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", "")))
+ block_text_parts.append(_normalize_text_content(span.content))
return "".join(block_text_parts)
@@ -346,22 +332,22 @@ def _normalize_text_content(content: str) -> str:
return full_to_half_exclude_marks(content or "")
-def _render_span(span: Span, escape_markdown: bool = True) -> str | None:
+def _render_span(span: Span, escape_markdown: bool = True) -> tuple[str, str] | None:
# 将单个 span 渲染成 markdown 片段。
# 这里只负责“渲染成什么文本”,不决定后面是否补空格。
span_type = span.type
content = ""
if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.get("content", ""))
+ content = _normalize_text_content(span.content)
if escape_markdown:
content = escape_special_markdown_char(content)
elif span_type == ContentType.INLINE_EQUATION:
- if span.get("content", ""):
- content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
+ if span.content:
+ content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"
elif span_type == ContentType.INTERLINE_EQUATION:
- if span.get("content", ""):
- content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
+ if span.content:
+ content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"
else:
return None
@@ -374,7 +360,7 @@ def _render_span(span: Span, escape_markdown: bool = True) -> str | None:
def _join_rendered_span(
para_block: Block, block_lang: str, line: Line, line_idx: int, span_idx: int, span_type: str, content: str
-) -> str:
+) -> tuple[str, str]:
# 根据语言和上下文决定当前 span 后面的分隔符。
# 这里集中处理:
# 1. CJK 与西文的空格差异
@@ -423,7 +409,7 @@ def _next_line_starts_with_lowercase_text(para_block: Block, line_idx: int) -> b
if next_span.type != ContentType.TEXT:
return False
- next_content = _normalize_text_content(next_span.get("content", ""))
+ next_content = _normalize_text_content(next_span.content)
return bool(next_content) and next_content[0].islower()
@@ -473,7 +459,7 @@ def _build_bbox(para_bbox: BBox, page_size: list[int]) -> IntBBox | None:
def _get_ref_text_item_blocks(para_block: Block) -> list[Block]:
- return para_block.get("blocks") or [para_block]
+ return para_block.blocks or [para_block]
def _split_list_item_blocks(para_block: Block) -> list[Block]:
@@ -508,16 +494,16 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
for span in line.spans:
span_type = span.type
if span_type == ContentType.TABLE:
- return span.get("image_path", ""), span.get("html", "")
+ return span.image_path, span.html
if span_type == ContentType.CHART:
- return span.get("image_path", ""), span.get("content", "")
+ return span.image_path, span.content
if span_type == ContentType.IMAGE:
- return span.get("image_path", ""), _normalize_visual_content(span.get("content", ""))
+ return span.image_path, _normalize_visual_content(span.content)
if span_type == ContentType.INTERLINE_EQUATION:
- return span.get("image_path", ""), span.get("content", "")
+ return span.image_path, span.content
return "", ""
- if "blocks" in para_block:
+ if para_block.blocks:
for block in para_block.blocks:
block_type = block.type
if block_type in [
@@ -534,9 +520,9 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
return get_data_from_spans(para_block.lines)
-def merge_para_with_text_v2(para_block: Block) -> str:
+def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
- para_content = []
+ para_content: list[dict[str, Any]] = []
para_type = para_block.type
for line_idx, line in enumerate(para_block.lines):
@@ -544,7 +530,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
span_type = span.type
if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.get("content", ""))
+ content = _normalize_text_content(span.content)
if not content.strip():
continue
@@ -575,7 +561,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
}
)
elif span_type == ContentType.INLINE_EQUATION:
- content = span.get("content", "").strip()
+ content = span.content.strip()
if content:
para_content.append(
{
@@ -594,10 +580,10 @@ def merge_para_with_text_v2(para_block: Block) -> str:
def make_blocks_to_content_list(
- para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]
-) -> list[dict[str, Any]] | None:
+ para_block: Block, img_bucket_path: str, page_idx: int, page_size: list[int]
+) -> dict[str, Any] | None:
para_type = para_block.type
- para_content = None
+ para_content: dict[str, Any] | None = None
if para_type in [
BlockType.TEXT,
BlockType.INDEX,
@@ -638,30 +624,30 @@ def make_blocks_to_content_list(
if title_level != 0:
para_content["text_level"] = title_level
elif para_type == BlockType.INTERLINE_EQUATION:
- if len(para_block.lines) == 0 or len(para_block.lines[0]["spans"]) == 0:
+ if len(para_block.lines) == 0 or len(para_block.lines[0].spans) == 0:
return None
para_content = {
"type": ContentType.EQUATION,
- "img_path": f"{img_buket_path}/{para_block['lines'][0]['spans'][0].get('image_path', '')}",
+ "img_path": f"{img_bucket_path}/{para_block.lines[0].spans[0].image_path}",
}
- if para_block.lines[0]["spans"][0].get("content", ""):
+ if para_block.lines[0].spans[0].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: []}
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_bucket_path}/{image_path}"
if image_content:
para_content["content"] = image_content
_apply_visual_sub_type(para_content, para_block)
for block in para_block.blocks:
if block.type == BlockType.IMAGE_BODY:
- for line in block["lines"]:
+ 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 span.image_path:
+ para_content["img_path"] = f"{img_bucket_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:
@@ -670,17 +656,13 @@ def make_blocks_to_content_list(
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 line in block.lines:
for span in line.spans:
if span.type == ContentType.TABLE:
- if span.get("html", ""):
- para_content[BlockType.TABLE_BODY] = _format_embedded_html(
- span["html"],
- img_buket_path,
- )
-
- if span.get("image_path", ""):
- para_content["img_path"] = f"{img_buket_path}/{span['image_path']}"
+ if span.html:
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)
+ if span.image_path:
+ para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"
if block.type == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
@@ -696,10 +678,10 @@ def make_blocks_to_content_list(
}
for block in para_block.blocks:
if block.type == BlockType.CHART_BODY:
- for line in block["lines"]:
+ 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 span.type == ContentType.CHART and span.image_path:
+ para_content["img_path"] = f"{img_bucket_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:
@@ -707,7 +689,7 @@ def make_blocks_to_content_list(
elif para_type == BlockType.CODE:
para_content = {
"type": BlockType.CODE,
- "sub_type": para_block["sub_type"],
+ "sub_type": para_block.sub_type,
BlockType.CODE_CAPTION: [],
BlockType.CODE_FOOTNOTE: [],
}
@@ -723,7 +705,7 @@ def make_blocks_to_content_list(
if not para_content:
return None
- bbox = _build_bbox(para_block.get("bbox"), page_size)
+ bbox = _build_bbox(para_block.bbox, page_size)
if bbox:
para_content["bbox"] = bbox
para_content["page_idx"] = page_idx
@@ -731,7 +713,7 @@ def make_blocks_to_content_list(
return para_content
-def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> list[dict[str, Any]] | None:
+def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: list[int]) -> dict[str, Any] | None:
para_type = para_block.type
para_content = None
@@ -794,7 +776,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"content": {
"math_content": math_content,
"math_type": "latex",
- "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_source": {"path": f"{img_bucket_path}/{image_path}"},
},
}
elif para_type == BlockType.IMAGE:
@@ -809,7 +791,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
para_content = {
"type": ContentTypeV2.IMAGE,
"content": {
- "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_source": {"path": f"{img_bucket_path}/{image_path}"},
"image_caption": image_caption,
"image_footnote": image_footnote,
},
@@ -821,7 +803,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
table_caption = []
table_footnote = []
image_path, html = _get_body_data(para_block)
- table_html = _format_embedded_html(html, img_buket_path)
+ table_html = _format_embedded_html(html, img_bucket_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_type = ContentTypeV2.TABLE_COMPLEX
@@ -835,7 +817,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
para_content = {
"type": ContentTypeV2.TABLE,
"content": {
- "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_source": {"path": f"{img_bucket_path}/{image_path}"},
"table_caption": table_caption,
"table_footnote": table_footnote,
"html": table_html,
@@ -855,7 +837,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
para_content = {
"type": ContentTypeV2.CHART,
"content": {
- "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_source": {"path": f"{img_bucket_path}/{image_path}"},
"content": "",
"chart_caption": chart_caption,
"chart_footnote": chart_footnote,
@@ -873,7 +855,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
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,
@@ -881,7 +863,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"code_caption": code_caption,
"code_content": code_content,
"code_footnote": code_footnote,
- "code_language": para_block.get("guess_lang", "txt"),
+ "code_language": para_block.guess_lang or "txt",
},
}
elif sub_type == BlockType.ALGORITHM:
@@ -928,7 +910,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"type": ContentTypeV2.LIST,
"content": {
"list_type": ContentTypeV2.LIST_TEXT,
- "attribute": para_block.get("attribute", "unordered"),
+ "attribute": para_block._list_attribute or "unordered",
"list_items": list_items,
},
}
@@ -953,7 +935,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
if not para_content:
return None
- bbox = _build_bbox(para_block.get("bbox"), page_size)
+ bbox = _build_bbox(para_block.bbox, page_size)
if bbox:
para_content["bbox"] = bbox
@@ -963,48 +945,54 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
def union_make(
pdf_info_dict: list[dict[str, Any]],
make_mode: str,
- img_buket_path: str = "",
-) -> str:
- output_content = []
+ img_bucket_path: str = "",
+) -> str | list[dict[str, Any]] | list[list[dict[str, Any]]] | None:
+ output_markdowns: list[str] = []
+ output_content_items: list[dict[str, Any]] = []
+ output_content_lists: list[list[dict[str, Any]]] = []
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")
+ page_idx = page_info.get("page_idx") or 0
+ page_size = page_info.get("page_size") or []
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)
+ page_markdown = make_blocks_to_markdown(paras_of_layout, make_mode, img_bucket_path)
+ output_markdowns.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 []))
if not para_blocks:
continue
for para_block in para_blocks:
- para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
+ para_content = make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)
if para_content:
- output_content.append(para_content)
+ output_content_items.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 []))
- page_contents = []
+ page_contents: list[dict[str, Any]] = []
if para_blocks:
for para_block in para_blocks:
- para_content = make_blocks_to_content_list_v2(para_block, img_buket_path, page_size)
+ para_content = make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)
if para_content:
page_contents.append(para_content)
- output_content.append(page_contents)
+ output_content_lists.append(page_contents)
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
- return "\n\n".join(output_content)
- elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:
- return output_content
+ return "\n\n".join(output_markdowns)
+ elif make_mode == MakeMode.CONTENT_LIST:
+ return output_content_items
+ elif make_mode == MakeMode.CONTENT_LIST_V2:
+ return output_content_lists
else:
logger.error(f"Unsupported make mode: {make_mode}")
return None
def get_title_level(block: Block) -> int:
- title_level = block.get("level", 1)
+ title_level = block.level
+ if title_level is None:
+ title_level = 1
if title_level < 1:
title_level = 0
return title_level
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 0423494c..793de020 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -8,7 +8,7 @@ across backends.
from __future__ import annotations
import copy
-from typing import Any, Callable, Iterator, TypeVar
+from typing import Any, Callable, Iterator, TypeVar, Union
from tqdm import tqdm
@@ -28,7 +28,11 @@ def build_middle_json(
image_writer: DataWriter,
*,
init_fn: Callable[..., dict[str, Any]],
- page_cvt_fn: Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
+ page_cvt_fn: Union[
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int, bool], PageInfo],
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int, bool, bool], PageInfo],
+ ],
finalize_fn: Callable[..., None],
**kwargs: Any,
) -> dict[str, Any]:
@@ -71,7 +75,11 @@ def append_pages(
pdf_doc: Any,
image_writer: DataWriter | None,
*,
- page_cvt_fn: Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
+ page_cvt_fn: Union[
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int], PageInfo],
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int, bool], PageInfo],
+ Callable[[T, dict[str, Any], Any, DataWriter | None, int, bool, bool], PageInfo],
+ ],
page_start_index: int = 0,
progress_bar: Any = None,
**kwargs: Any,
@@ -96,7 +104,7 @@ def append_pages(
page_info = PageInfo(
preproc_blocks=[],
page_idx=page_index,
- page_size=[page_w, page_h],
+ page_size=(page_w, page_h),
discarded_blocks=[],
)
finally:
@@ -120,10 +128,10 @@ def apply_post_ocr(pdf_info_list: list[PageInfo], ocr_model: Any) -> None:
for blocks in [page_info.preproc_blocks, page_info.discarded_blocks]:
for block in blocks:
for span in _iter_block_spans(block):
- if "np_img" in span:
+ if span._np_img:
need_ocr_list.append(span)
- img_crop_list.append(rotate_vertical_crop_if_needed(span["np_img"]))
- span.pop("np_img")
+ img_crop_list.append(rotate_vertical_crop_if_needed(span._np_img))
+ span._np_img = None
if not img_crop_list:
return
diff --git a/mineru/backend/utils/office_chart.py b/mineru/backend/utils/office_chart.py
index 7b2ba157..9c23822f 100644
--- a/mineru/backend/utils/office_chart.py
+++ b/mineru/backend/utils/office_chart.py
@@ -218,7 +218,7 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:
if axis is None:
axis = plot_area.find("c:catAx", namespaces=_NS)
if axis is not None:
- category_axis_title = _extract_title_text(axis.find("c:title", namespaces=_NS))
+ category_axis_title = _extract_title_text(axis.find("c:title", namespaces=_NS)) # type: ignore
x_axis_title = ""
value_axis_title = ""
@@ -226,7 +226,7 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:
for axis in plot_area.findall("c:valAx", namespaces=_NS):
axis_pos = axis.find("c:axPos", namespaces=_NS)
axis_position = axis_pos.get("val") if axis_pos is not None else ""
- title = _extract_title_text(axis.find("c:title", namespaces=_NS))
+ title = _extract_title_text(axis.find("c:title", namespaces=_NS)) # type: ignore
if axis_position == "b" and not x_axis_title:
x_axis_title = title
elif axis_position == "l" and not value_axis_title:
@@ -236,40 +236,40 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:
else:
axis = plot_area.find("c:valAx", namespaces=_NS)
if axis is not None:
- value_axis_title = _extract_title_text(axis.find("c:title", namespaces=_NS))
+ value_axis_title = _extract_title_text(axis.find("c:title", namespaces=_NS)) # type: ignore
series_specs = []
for _, plot_element in plot_elements:
for series_element in plot_element.findall("c:ser", namespaces=_NS):
series_specs.append(
SeriesSpec(
- name_formula=_extract_tx_formula(series_element.find("c:tx", namespaces=_NS)),
- literal_name=_extract_tx_text(series_element.find("c:tx", namespaces=_NS)),
- cat_formula=_extract_reference_formula(series_element.find("c:cat", namespaces=_NS)),
- x_formula=_extract_reference_formula(series_element.find("c:xVal", namespaces=_NS)),
- val_formula=_extract_reference_formula(series_element.find("c:val", namespaces=_NS)),
- y_formula=_extract_reference_formula(series_element.find("c:yVal", namespaces=_NS)),
- bubble_size_formula=_extract_reference_formula(series_element.find("c:bubbleSize", namespaces=_NS)),
+ name_formula=_extract_tx_formula(series_element.find("c:tx", namespaces=_NS)), # type: ignore
+ literal_name=_extract_tx_text(series_element.find("c:tx", namespaces=_NS)), # type: ignore
+ cat_formula=_extract_reference_formula(series_element.find("c:cat", namespaces=_NS)), # type: ignore
+ x_formula=_extract_reference_formula(series_element.find("c:xVal", namespaces=_NS)), # type: ignore
+ val_formula=_extract_reference_formula(series_element.find("c:val", namespaces=_NS)), # type: ignore
+ y_formula=_extract_reference_formula(series_element.find("c:yVal", namespaces=_NS)), # type: ignore
+ bubble_size_formula=_extract_reference_formula(series_element.find("c:bubbleSize", namespaces=_NS)), # type: ignore
cached_categories=_extract_reference_cache(
- series_element.find("c:cat", namespaces=_NS),
+ series_element.find("c:cat", namespaces=_NS), # type: ignore
date_hint=has_date_axis,
date_1904=_chart_uses_date_1904(root),
),
- cached_x_values=_extract_reference_cache(series_element.find("c:xVal", namespaces=_NS)),
+ cached_x_values=_extract_reference_cache(series_element.find("c:xVal", namespaces=_NS)), # type: ignore
cached_values=_extract_reference_cache(
_first_non_none(
series_element.find("c:val", namespaces=_NS),
series_element.find("c:yVal", namespaces=_NS),
- )
+ ) # type: ignore
),
- cached_bubble_sizes=_extract_reference_cache(series_element.find("c:bubbleSize", namespaces=_NS)),
+ cached_bubble_sizes=_extract_reference_cache(series_element.find("c:bubbleSize", namespaces=_NS)), # type: ignore
)
)
return ChartSpec(
chart_type=(plot_elements[0][0] if len(plot_elements) == 1 else "comboChart"),
plot_kind=plot_kind,
- title=_extract_title_text(root.find(".//c:chart/c:title", namespaces=_NS)),
+ title=_extract_title_text(root.find(".//c:chart/c:title", namespaces=_NS)), # type: ignore
category_axis_title=category_axis_title,
value_axis_title=value_axis_title,
x_axis_title=x_axis_title,
diff --git a/mineru/backend/utils/span_block_fix.py b/mineru/backend/utils/span_block_fix.py
index 54cc8ec8..97eb8ff7 100644
--- a/mineru/backend/utils/span_block_fix.py
+++ b/mineru/backend/utils/span_block_fix.py
@@ -33,20 +33,20 @@ def is_vertical_text_block_by_spans(spans: list[Span]) -> bool:
def fix_text_block(block: Block) -> Block:
# 文本block中的公式span都应该转换成行内type
- for span in block._extra["spans"]:
+ for span in block._fix_spans:
if span.type == ContentType.INTERLINE_EQUATION:
span.type = ContentType.INLINE_EQUATION
- if is_vertical_text_block_by_spans(block._extra["spans"]):
+ if is_vertical_text_block_by_spans(block._fix_spans):
# 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block._extra["spans"])
+ block_lines = merge_spans_to_vertical_line(block._fix_spans)
sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)
else:
- block_lines = merge_spans_to_line(block._extra["spans"])
+ block_lines = merge_spans_to_line(block._fix_spans)
sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
block.lines = sort_block_lines
- del block._extra["spans"]
+ block._fix_spans = []
return block
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index cc8da451..3ef8885d 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -42,7 +42,7 @@ def txt_spans_extract(
pdf_page: Any,
spans: list[Span],
pil_img: Any,
- scale: int,
+ scale: float,
all_bboxes: list[tuple[Any, ...]],
all_discarded_blocks: list[tuple[Any, ...]],
) -> list[Span]:
@@ -68,7 +68,7 @@ def txt_spans_extract(
)
page_all_chars = [char for char in page_chars["chars"] if _is_supported_rotation(char["rotation"])]
- # 计算所有sapn的高度的中位数
+ # 计算所有span的高度的中位数
span_height_list = []
for span in spans:
if span.type in [ContentType.TEXT]:
@@ -143,7 +143,7 @@ def _prepare_post_ocr_spans(
need_ocr_spans: list[Span],
spans: list[Span],
pil_img: Any,
- scale: int,
+ scale: float,
) -> list[Span]:
if len(need_ocr_spans) == 0:
return spans
@@ -160,7 +160,7 @@ def _prepare_post_ocr_spans(
span.content = ""
span.score = 1.0
- span._extra["np_img"] = span_img
+ span._np_img = span_img
return spans
diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.py
index 97f413bd..0ecbe5d9 100644
--- a/mineru/backend/utils/table_merge.py
+++ b/mineru/backend/utils/table_merge.py
@@ -8,7 +8,7 @@ from typing import Any
from bs4 import BeautifulSoup, Tag
from ...types import BBox, Block, PageInfo, Span
-from ...utils.enum_class import BlockType, SplitFlag
+from ...utils.enum_class import BlockType
from ..vlm.vlm_middle_json_mkcontent import merge_para_with_text
from .char_utils import full_to_half
from .table_continuation import is_table_continuation_text
@@ -192,16 +192,12 @@ def _find_table_body_block(table_block: Block) -> Block | None:
return None
-def _build_post_body_child_index(table_block: Block, offset: int) -> int | float | None:
+def _build_post_body_child_index(table_block: Block, offset: int) -> int | None:
"""为跨页搬运到上一页表格的子块生成表体后的安全 index。"""
body_block = _find_table_body_block(table_block)
if body_block is None:
return None
-
body_index = body_block.index
- if not isinstance(body_index, (int, float)):
- return None
-
return body_index + offset
@@ -278,7 +274,7 @@ def _refresh_table_state_metrics(state: TableMergeState) -> None:
state.front_header_info, state.front_first_data_row_metrics = _build_front_cache(state.rows)
-def build_table_state_from_html(
+def _build_table_state_from_html(
html: str,
max_header_rows: int = MAX_HEADER_ROWS,
) -> TableMergeState | None:
@@ -361,7 +357,7 @@ def _get_or_create_table_state(
def _serialize_table_state_html(state: TableMergeState) -> None:
- state.body_span._extra["html"] = str(state.soup)
+ state.body_span.html = str(state.soup)
state.dirty = False
@@ -1093,11 +1089,11 @@ def perform_table_merge(
previous_table_block.blocks = [block for block in previous_table_block.blocks if block.type != BlockType.TABLE_FOOTNOTE]
for footnote_offset, table_footnote in enumerate(wait_merge_table_footnotes, start=1):
- temp_table_footnote = table_footnote.copy()
- temp_table_footnote._extra[SplitFlag.CROSS_PAGE] = True
+ temp_table_footnote = deepcopy(table_footnote)
+ temp_table_footnote._cross_page = True
post_body_index = _build_post_body_child_index(previous_table_block, footnote_offset)
if post_body_index is None:
- temp_table_footnote._extra.pop("index", None)
+ temp_table_footnote.index = 0
else:
temp_table_footnote.index = post_body_index
previous_table_block.blocks.append(temp_table_footnote)
diff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.py
index e5f8d205..8834a6e8 100644
--- a/mineru/backend/utils/visual_magic_model_utils.py
+++ b/mineru/backend/utils/visual_magic_model_utils.py
@@ -99,7 +99,7 @@ def clean_content(content: str | None) -> str | None:
return content
-def fallback_inline_caption_fragments(blocks: list[Block], visual_main_types: dict[Any, Any] | set[Any]) -> None:
+def fallback_inline_caption_fragments(blocks: list[Block], visual_main_types: dict[str, str] | set[str]) -> None:
"""将紧贴视觉主体上方的同行 text/footnote 片段兜底为通用 caption。"""
if len(blocks) < 3:
return
@@ -214,7 +214,7 @@ def _is_leading_continuation_cluster_near_table(leading_blocks: list[Block], tab
return True
-def fallback_stacked_table_caption_fragments(blocks: list[Block], visual_main_types: dict[Any, Any] | set[Any]) -> None:
+def fallback_stacked_table_caption_fragments(blocks: list[Block], visual_main_types: dict[str, str] | set[str]) -> None:
"""将 table 上方紧贴标题簇里的 text/footnote 片段兜底为 caption。"""
table_main_types = get_table_main_types(visual_main_types)
if not table_main_types:
@@ -239,7 +239,7 @@ def fallback_stacked_table_caption_fragments(blocks: list[Block], visual_main_ty
block.merge_prev = False
-def get_table_main_types(visual_main_types: dict[Any, Any] | set[Any]) -> set[Any]:
+def get_table_main_types(visual_main_types: dict[str, str] | set[str]) -> set[str]:
"""根据调用方传入的视觉主体类型,找出 table 对应的主体类型。"""
if isinstance(visual_main_types, dict):
return {block_type for block_type, visual_type in visual_main_types.items() if visual_type == BlockType.TABLE}
@@ -366,7 +366,7 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],
for main_block in main_blocks:
if main_block.index in sub_images_by_index:
- main_block._extra["sub_images"] = sub_images_by_index[main_block.index]
+ main_block._sub_images = sub_images_by_index[main_block.index]
for child_block in child_blocks:
parent_block = find_best_visual_parent(
@@ -394,7 +394,7 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],
mapping = VISUAL_TYPE_MAPPING[visual_type]
body_block = deepcopy(main_block)
body_block.type = mapping["body"]
- body_block.pop("sub_images", None)
+ body_block._sub_images = []
body_block.sub_type = ""
captions = []
@@ -423,8 +423,8 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],
)
if visual_type in [BlockType.IMAGE, BlockType.CHART] and main_block.sub_type:
two_layer_block.sub_type = main_block.sub_type
- if visual_type == BlockType.IMAGE and main_block._extra.get("sub_images"):
- two_layer_block["sub_images"] = main_block._extra["sub_images"]
+ if visual_type == BlockType.IMAGE and main_block._sub_images:
+ two_layer_block._sub_images = main_block._sub_images
if visual_type == BlockType.TABLE and main_block._cell_merge:
two_layer_block._cell_merge = main_block._cell_merge
two_layer_block.blocks.sort(key=lambda x: x.index or 0)
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index 49b4143c..0e8c9865 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -82,7 +82,7 @@ def blocks_to_page_info(
page_info = PageInfo(
preproc_blocks=blocks,
discarded_blocks=discarded_blocks,
- page_size=[width, height],
+ page_size=(width, height),
page_idx=page_index,
)
return page_info
@@ -107,7 +107,7 @@ def finalize_middle_json(pdf_info_list: list[PageInfo]) -> None:
def result_to_middle_json(
- model_output_blocks_list: list[list[dict[str, Any]]],
+ model_output_blocks_list: list[ExtractResult],
images_list: list[dict[str, Any]],
pdf_doc: Any,
image_writer: DataWriter,
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index f143774b..d76f26df 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -9,7 +9,7 @@ import os
import threading
import time
from contextlib import asynccontextmanager, contextmanager
-from typing import Any, AsyncIterator, Generator, Iterator
+from typing import Any, AsyncIterator, Generator, Iterator, Literal
import pypdfium2 as pdfium
from loguru import logger
@@ -50,7 +50,14 @@ class ModelSingleton:
def get_model(
self,
- backend: str,
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ],
model_path: str | None,
server_url: str | None,
**kwargs: Any,
@@ -273,7 +280,14 @@ class ModelSingleton:
async def _get_model_async(
- backend: str,
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ],
model_path: str | None,
server_url: str | None,
**kwargs: Any,
@@ -429,12 +443,19 @@ def doc_analyze(
pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend: str = "transformers",
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ] = "transformers",
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
**kwargs: Any,
-) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:
+) -> tuple[dict[str, Any], list[ExtractResult]]:
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)
@@ -523,12 +544,19 @@ async def aio_doc_analyze(
pdf_bytes: bytes,
image_writer: DataWriter | None,
predictor: MinerUClient | None = None,
- backend: str = "transformers",
+ backend: Literal[
+ "http-client",
+ "transformers",
+ "mlx-engine",
+ "lmdeploy-engine",
+ "vllm-engine",
+ "vllm-async-engine",
+ ] = "transformers",
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
**kwargs: Any,
-) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:
+) -> tuple[dict[str, Any], list[ExtractResult]]:
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)
@@ -536,7 +564,7 @@ async def aio_doc_analyze(
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)
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index ac1e5c2f..9bde1ed3 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -187,7 +187,7 @@ class MagicModel:
span = Span(
type=span_type,
bbox=block_bbox,
- content=block_content,
+ content=block_content or "",
)
# 处理span类型并添加到all_spans
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index 3fed5456..67c8d7de 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -28,14 +28,14 @@ inline_left_delimiter = delimiters["inline"]["left"]
inline_right_delimiter = delimiters["inline"]["right"]
-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:
+def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:
+ """Prefix non-data image sources in table HTML with img_bucket_path."""
+ if not html or not img_bucket_path:
return html
return re.sub(
r'src="(?!data:)([^"]+)"',
- lambda match: f'src="{img_buket_path}/{match.group(1)}"',
+ lambda match: f'src="{img_bucket_path}/{match.group(1)}"',
html,
)
@@ -53,9 +53,9 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
)
-def _format_embedded_html(html: str, img_buket_path: str) -> str:
+def _format_embedded_html(html: str, img_bucket_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))
+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))
def _normalize_text_content(content: str | None) -> str:
@@ -81,12 +81,12 @@ def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int
return False
-def _build_media_path(img_buket_path: str, image_path: str) -> str:
+def _build_media_path(img_bucket_path: str, image_path: str) -> str:
if not image_path:
return ""
- if not img_buket_path:
+ if not img_bucket_path:
return image_path
- return f"{img_buket_path}/{image_path}"
+ return f"{img_bucket_path}/{image_path}"
def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
@@ -108,10 +108,10 @@ def _build_visual_details_block(content: str, span_type: str, summary_override:
def _build_visual_body_segments(
- image_path: str, content: str, img_buket_path: str, span_type: str, summary_override: str = ""
+ image_path: str, content: str, img_bucket_path: str, span_type: str, summary_override: str = ""
) -> list[tuple[str, str]]:
body_segments = []
- media_path = _build_media_path(img_buket_path, image_path)
+ media_path = _build_media_path(img_bucket_path, image_path)
if media_path:
body_segments.append((f"![]({media_path})", "markdown_line"))
@@ -145,7 +145,7 @@ def _render_code_block_markdown(block: Block, para_block: Block) -> str:
def _render_visual_block_segments(
- block: Block, para_block: Block, img_buket_path: str = "", table_enable: bool = True
+ block: Block, para_block: Block, img_bucket_path: str = "", table_enable: bool = True
) -> list[tuple[str, str]]:
block_type = block.type
@@ -174,7 +174,7 @@ def _render_visual_block_segments(
_build_visual_body_segments(
span.image_path,
span.content,
- img_buket_path,
+ img_bucket_path,
ContentType.IMAGE,
summary_override=para_block.sub_type,
)
@@ -191,7 +191,7 @@ def _render_visual_block_segments(
_build_visual_body_segments(
span.image_path,
span.content,
- img_buket_path,
+ img_bucket_path,
ContentType.CHART,
summary_override=para_block.sub_type,
)
@@ -207,14 +207,14 @@ def _render_visual_block_segments(
if table_enable and span.html:
rendered_segments.append(
(
- _format_embedded_html(span.html, img_buket_path),
+ _format_embedded_html(span.html, img_bucket_path),
"html_block",
)
)
elif span.image_path:
rendered_segments.append(
(
- f"![]({_build_media_path(img_buket_path, span.image_path)})",
+ f"![]({_build_media_path(img_bucket_path, span.image_path)})",
"markdown_line",
)
)
@@ -235,20 +235,20 @@ def _get_visual_block_separator(prev_segment_kind: str, current_segment_kind: st
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_bucket_path: str = "", table_enable: bool = True) -> str:
rendered_segments = []
for block in _get_blocks_in_index_order(para_block.blocks):
rendered_segments.extend(
_render_visual_block_segments(
block,
para_block,
- img_buket_path,
+ img_bucket_path,
table_enable=table_enable,
)
)
para_text = ""
- prev_segment_kind = None
+ prev_segment_kind = ""
for segment_text, segment_kind in rendered_segments:
if para_text:
para_text += _get_visual_block_separator(prev_segment_kind, segment_kind)
@@ -261,7 +261,7 @@ def _merge_visual_blocks_to_markdown(para_block: Block, img_buket_path: str = ""
def merge_para_with_text(
para_block: Block,
formula_enable: bool = True,
- img_buket_path: str = "",
+ img_bucket_path: str = "",
escape_text_block_prefix: bool = True,
) -> str:
block_text = ""
@@ -289,7 +289,7 @@ def merge_para_with_text(
content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"
else:
if span.image_path:
- content = f"![]({img_buket_path}/{span.image_path})"
+ content = f"![]({img_bucket_path}/{span.image_path})"
content = content.strip()
if content:
@@ -337,20 +337,20 @@ def merge_para_with_text(
def mk_blocks_to_markdown(
- para_blocks: list[Block], make_mode: str, formula_enable: bool, table_enable: bool, img_buket_path: str = ""
+ para_blocks: list[Block], make_mode: str, formula_enable: bool, table_enable: bool, img_bucket_path: str = ""
) -> list[str]:
page_markdown: list[str] = []
for para_block in para_blocks:
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)
+ para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_bucket_path=img_bucket_path)
elif para_type == BlockType.LIST:
for block in para_block.blocks:
item_text = merge_para_with_text(
block,
formula_enable=formula_enable,
- img_buket_path=img_buket_path,
+ img_bucket_path=img_bucket_path,
escape_text_block_prefix=False,
)
para_text += f"{item_text} \n"
@@ -363,7 +363,7 @@ def mk_blocks_to_markdown(
elif make_mode == MakeMode.MM_MD:
para_text = _merge_visual_blocks_to_markdown(
para_block,
- img_buket_path,
+ img_bucket_path,
table_enable=table_enable,
)
@@ -373,7 +373,7 @@ def mk_blocks_to_markdown(
elif make_mode == MakeMode.MM_MD:
para_text = _merge_visual_blocks_to_markdown(
para_block,
- img_buket_path,
+ img_bucket_path,
table_enable=table_enable,
)
elif para_type == BlockType.CHART:
@@ -382,13 +382,13 @@ def mk_blocks_to_markdown(
elif make_mode == MakeMode.MM_MD:
para_text = _merge_visual_blocks_to_markdown(
para_block,
- img_buket_path,
+ img_bucket_path,
table_enable=table_enable,
)
elif para_type == BlockType.CODE:
para_text = _merge_visual_blocks_to_markdown(
para_block,
- img_buket_path,
+ img_bucket_path,
table_enable=table_enable,
)
@@ -401,9 +401,10 @@ def mk_blocks_to_markdown(
return page_markdown
-def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx: int, page_size: list[int]) -> dict[str, Any]:
+def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_idx: int, page_size: list[int]) -> dict[str, Any]:
para_type = para_block.type
- para_content = {}
+ para_content: dict[str, Any] = {}
+
if para_type in [
BlockType.TEXT,
BlockType.REF_TEXT,
@@ -445,7 +446,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
elif para_type == BlockType.IMAGE:
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["img_path"] = _build_media_path(img_bucket_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:
@@ -461,9 +462,9 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
for span in line.spans:
if span.type == ContentType.TABLE:
if span.html:
- para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_buket_path)
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)
if span.image_path:
- para_content["img_path"] = f"{img_buket_path}/{span.image_path}"
+ para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"
if block.type == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
@@ -473,7 +474,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
image_path, chart_content = get_body_data(para_block)
para_content = {
"type": ContentType.CHART,
- "img_path": _build_media_path(img_buket_path, image_path),
+ "img_path": _build_media_path(img_bucket_path, image_path),
"content": chart_content if chart_content else "",
BlockType.CHART_CAPTION: [],
BlockType.CHART_FOOTNOTE: [],
@@ -512,7 +513,7 @@ def make_blocks_to_content_list(para_block: Block, img_buket_path: str, page_idx
return para_content
-def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> dict:
+def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: list[int]) -> dict:
para_type = para_block.type
para_content = {}
if para_type in [
@@ -568,7 +569,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"content": {
"math_content": math_content,
"math_type": "latex",
- "image_source": {"path": f"{img_buket_path}/{image_path}"},
+ "image_source": {"path": f"{img_bucket_path}/{image_path}"},
},
}
elif para_type == BlockType.IMAGE:
@@ -576,7 +577,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
image_footnote = []
image_path, image_content = get_body_data(para_block)
image_source = {
- "path": _build_media_path(img_buket_path, image_path),
+ "path": _build_media_path(img_bucket_path, image_path),
}
for block in para_block.blocks:
if block.type == BlockType.IMAGE_CAPTION:
@@ -597,9 +598,9 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
table_caption = []
table_footnote = []
image_path, html = get_body_data(para_block)
- table_html = _format_embedded_html(html, img_buket_path)
+ table_html = _format_embedded_html(html, img_bucket_path)
image_source = {
- "path": f"{img_buket_path}/{image_path}",
+ "path": f"{img_bucket_path}/{image_path}",
}
if table_html.count("<table") > 1:
table_nest_level = 2
@@ -639,7 +640,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_
"type": ContentTypeV2.CHART,
"content": {
"image_source": {
- "path": _build_media_path(img_buket_path, image_path),
+ "path": _build_media_path(img_bucket_path, image_path),
},
"content": chart_content if chart_content else "",
"chart_caption": chart_caption,
@@ -771,7 +772,7 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
return get_data_from_spans(para_block.lines)
-def merge_para_with_text_v2(para_block: Block) -> str:
+def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
block_text = ""
for line in para_block.lines:
for span in line.spans:
@@ -780,7 +781,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
block_text += span.content
block_lang = detect_lang(block_text)
- para_content = []
+ para_content: list[dict[str, Any]] = []
para_type = para_block.type
for i, line in enumerate(para_block.lines):
for j, span in enumerate(line.spans):
@@ -834,16 +835,10 @@ def merge_para_with_text_v2(para_block: Block) -> str:
# 合并相同类型的span
para_content[-1]["content"] += span_content
else:
- span_content = {
- "type": span_type,
- "content": span_content,
- }
+ span_content = {"type": span_type, "content": span_content}
para_content.append(span_content)
- elif span_type in [
- ContentTypeV2.SPAN_PHONETIC,
- ContentTypeV2.SPAN_EQUATION_INLINE,
- ]:
+ elif span_type in [ContentTypeV2.SPAN_PHONETIC, ContentTypeV2.SPAN_EQUATION_INLINE]:
span_content = {"type": span_type, "content": span.content}
para_content.append(span_content)
else:
@@ -854,7 +849,7 @@ def merge_para_with_text_v2(para_block: Block) -> str:
def union_make(
pdf_info_dict: list,
make_mode: str,
- img_buket_path: str = "",
+ img_bucket_path: str = "",
) -> str | list | None:
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")
@@ -868,14 +863,14 @@ def union_make(
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, formula_enable, table_enable, img_buket_path)
+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_bucket_path)
output_content.extend(page_markdown)
elif make_mode == MakeMode.CONTENT_LIST:
para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])
if not para_blocks:
continue
for para_block in para_blocks:
- para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
+ para_content = make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)
output_content.append(para_content)
elif make_mode == MakeMode.CONTENT_LIST_V2:
# https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md
@@ -883,7 +878,7 @@ def union_make(
page_contents = []
if para_blocks:
for para_block in para_blocks:
- para_content = make_blocks_to_content_list_v2(para_block, img_buket_path, page_size)
+ para_content = make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)
page_contents.append(para_content)
output_content.append(page_contents)
diff --git a/mineru/types.py b/mineru/types.py
index 2bd8236a..5eee3e0f 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -297,70 +297,6 @@ VISUAL_TYPE_MAPPING = {
}
-# ── dict-compatibility for dataclass-backed model objects ──────────
-#
-# Block / Line / Span / PageInfo are dataclasses whose canonical fields
-# are declared below. Backend code (MagicModel, para_split, union_make)
-# also attaches *internal processing fields* (``index``, ``page_num``,
-# ``_ocr_det_lines``, etc.) via ``block["key"] = value``. Those
-# non-canonical keys are stored in ``_extra`` so that the dataclass
-# signature stays clean while still providing full dict compatibility
-# during migration.
-
-
-def _extra_getitem(self, key: str) -> Any:
- try:
- return getattr(self, key)
- except AttributeError:
- pass
- try:
- return self._extra[key]
- except (AttributeError, KeyError):
- raise KeyError(key) from None
-
-
-def _extra_setitem(self, key: str, value: Any) -> None:
- if hasattr(self, key):
- setattr(self, key, value)
- else:
- self._extra[key] = value
-
-
-def _extra_get(self, key: str, default: Any = None) -> Any:
- try:
- val = getattr(self, key)
- except AttributeError:
- return self._extra.get(key, default)
- return default if val is None and default is not None else val
-
-
-def _extra_contains(self, key: str) -> bool:
- return hasattr(self, key) or key in self._extra
-
-
-def _extra_delitem(self, key: str) -> None:
- if hasattr(self, key):
- raise KeyError(f"Cannot delete canonical field '{key}'")
- del self._extra[key]
-
-
-def _extra_pop(self, key: str, default: Any = None) -> Any:
- val = _extra_get(self, key, default)
- if key in self._extra:
- del self._extra[key]
- return val
-
-
-def _install_dict_compat(*classes) -> None:
- for cls in classes:
- cls.__getitem__ = _extra_getitem
- cls.__setitem__ = _extra_setitem
- cls.__delitem__ = _extra_delitem
- cls.get = _extra_get
- cls.pop = _extra_pop
- cls.__contains__ = _extra_contains
-
-
# ── model types ─────────────────────────────────────────────────────
BBox: TypeAlias = tuple[float, float, float, float]
@@ -385,6 +321,11 @@ class Span:
# Internal
_cross_page: bool = False
+ _np_img: Any = None
+
+ _url: str = ""
+ _style: list[str] = field(default_factory=list)
+ _children: list[Span] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict) -> Span:
@@ -444,6 +385,12 @@ class Block:
section_number: str = ""
html: str = ""
+ # Office
+ anchor: str = ""
+ start: int | None = None
+ ilevel: int | None = None
+ is_numbered_style: bool = False
+
# Internal
_cross_page: bool = False
_lines_deleted: bool = False
@@ -451,6 +398,11 @@ class Block:
_line_avg_height: int = 0
_cell_merge: list[int] = field(default_factory=list)
_fix_spans: list[Span] = field(default_factory=list)
+ _list_attribute: str = ""
+ _page_num: int | None = None
+ _page_size: tuple[float, float] | None = None
+ _bbox_fs: BBox | None = None
+ _sub_images: list[Block] = field(default_factory=list)
_extra: dict = field(default_factory=dict)
@@ -485,7 +437,7 @@ class PageInfo:
"""Parsed content of a single page."""
page_idx: int
- page_size: tuple[int, int] | list[int, int] | None = None
+ page_size: tuple[int, int] | None = None
preproc_blocks: list[Block] = field(default_factory=list)
para_blocks: list[Block] = field(default_factory=list)
discarded_blocks: list[Block] = field(default_factory=list)
@@ -501,6 +453,3 @@ class PageInfo:
para_blocks=[Block.from_dict(b) for b in d.get("para_blocks", [])],
discarded_blocks=[Block.from_dict(b) for b in d.get("discarded_blocks", [])],
)
-
-
-_install_dict_compat(Span, Line, Block, PageInfo)
diff --git a/mineru/utils/bbox_utils.py b/mineru/utils/bbox_utils.py
index 29113d76..6ea7f54f 100644
--- a/mineru/utils/bbox_utils.py
+++ b/mineru/utils/bbox_utils.py
@@ -7,7 +7,7 @@ from ..types import BBox, IntBBox
def normalize_to_int_bbox(
- box: list[float] | BBox | None,
+ box: list[list[float]] | list[float] | BBox | None,
image_size: tuple[int, int] | None = None,
) -> IntBBox | None:
if box is None:
diff --git a/mineru/utils/cut_image.py b/mineru/utils/cut_image.py
index 0daa1060..da09f958 100644
--- a/mineru/utils/cut_image.py
+++ b/mineru/utils/cut_image.py
@@ -24,9 +24,9 @@ def cut_image_and_table(
span_type = span.type
if not check_img_bbox(span.bbox) or not image_writer:
- span._extra["image_path"] = ""
+ span.image_path = ""
else:
- span._extra["image_path"] = cut_image(
+ span.image_path = cut_image(
span.bbox,
page_id,
page_pil_img,
diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.py
index b3a667e5..bb25bf38 100644
--- a/mineru/utils/draw_bbox.py
+++ b/mineru/utils/draw_bbox.py
@@ -10,7 +10,7 @@ from pypdf import PageObject, PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from ..types import BBox, Block, PageInfo, Span
-from .enum_class import BlockType, ContentType, SplitFlag
+from .enum_class import BlockType, ContentType
# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。
TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {
@@ -203,7 +203,7 @@ def draw_layout_bbox(
elif nested_block.type == BlockType.TABLE_CAPTION:
tables_caption.append(bbox)
elif nested_block.type == BlockType.TABLE_FOOTNOTE:
- if nested_block._extra.get(SplitFlag.CROSS_PAGE, False):
+ if nested_block._cross_page:
continue
tables_footnote.append(bbox)
elif block.type == BlockType.IMAGE:
@@ -277,7 +277,7 @@ def draw_layout_bbox(
page_block_list.append(bbox)
elif block.type in [BlockType.IMAGE, BlockType.CHART, BlockType.CODE, BlockType.TABLE]:
for sub_block in block.blocks:
- if sub_block._extra.get(SplitFlag.CROSS_PAGE, False):
+ if sub_block._cross_page:
continue
bbox = sub_block.bbox
page_block_list.append(bbox)
diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.py
index 12daea16..4d3797eb 100644
--- a/mineru/utils/model_utils.py
+++ b/mineru/utils/model_utils.py
@@ -39,11 +39,11 @@ TEXT_REGION_LABELS = {
}
-def _get_bbox(item: dict[str, Any]) -> BBox | None:
- bbox = item.get("bbox")
- if bbox is not None:
- xmin, ymin, xmax, ymax = bbox
- return float(xmin), float(ymin), float(xmax), float(ymax)
+def _get_bbox(item: dict[str, Any]) -> BBox:
+ bbox = item["bbox"]
+ assert bbox is not None
+ xmin, ymin, xmax, ymax = bbox
+ return float(xmin), float(ymin), float(xmax), float(ymax)
def _get_int_bbox(item: dict[str, Any]) -> IntBBox:
@@ -51,6 +51,11 @@ def _get_int_bbox(item: dict[str, Any]) -> IntBBox:
return math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)
+def _bbox_area(bbox: BBox | IntBBox) -> float:
+ xmin, ymin, xmax, ymax = bbox
+ return abs((xmax - xmin) * (ymax - ymin))
+
+
def crop_img(
input_res: dict[str, Any],
input_img: Image.Image | np.ndarray,
@@ -86,11 +91,11 @@ def crop_img(
return return_image, return_list
-def get_coords_and_area(block_with_poly: dict[str, Any]) -> tuple[float, float, float, float, float]:
+def get_bbox_and_area(block_with_poly: dict[str, Any]) -> tuple[BBox, float]:
"""Extract coordinates and area from a table."""
xmin, ymin, xmax, ymax = _get_bbox(block_with_poly)
area = (xmax - xmin) * (ymax - ymin)
- return xmin, ymin, xmax, ymax, area
+ return (xmin, ymin, xmax, ymax), area
def calculate_intersection(box1: BBox, box2: BBox) -> BBox | None:
@@ -107,18 +112,16 @@ def calculate_intersection(box1: BBox, box2: BBox) -> BBox | None:
return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax
-def is_inside(small_box: BBox, big_box: BBox, overlap_threshold: float = 0.8) -> bool:
+def is_inside(small_box: BBox, big_box: BBox, small_area: float, overlap_threshold: float = 0.8) -> bool:
"""Check if small_box is inside big_box by at least overlap_threshold."""
- intersection = calculate_intersection(small_box[:4], big_box[:4])
-
+ intersection = calculate_intersection(small_box, big_box)
if not intersection:
return False
intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
-
# Check if overlap exceeds threshold
- return intersection_area >= overlap_threshold * small_box[4]
+ return intersection_area >= overlap_threshold * small_area
def remove_nested_ocr_text_blocks(
@@ -131,18 +134,17 @@ def remove_nested_ocr_text_blocks(
if not ocr_res_list or len(layout_res) < 2:
return ocr_res_list, []
- layout_info = [(block, get_coords_and_area(block)) for block in layout_res]
+ layout_info = [(block, get_bbox_and_area(block)) for block in layout_res]
blocks_to_remove = []
for text_block in ocr_res_list:
- text_box = get_coords_and_area(text_block)
- text_area = text_box[4]
- for parent_block, parent_box in layout_info:
+ text_box, text_area = get_bbox_and_area(text_block)
+ for parent_block, (parent_box, parent_area) in layout_info:
if parent_block is text_block:
continue
- if parent_box[4] <= text_area * min_area_ratio:
+ if parent_area <= text_area * min_area_ratio:
continue
- if is_inside(text_box, parent_box, overlap_threshold):
+ if is_inside(text_box, parent_box, text_area, overlap_threshold):
blocks_to_remove.append(text_block)
break
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 5a852c37..22e187ed 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -79,7 +79,7 @@ class PDFDocument:
def page_size(self, page_idx: int) -> tuple[float, float]:
page = self._get_page(page_idx)
with pdfium_guard():
- rect = page.get_bbox()
+ rect: tuple[float, float, float, float] = page.get_bbox()
return (abs(rect[2] - rect[0]), abs(rect[1] - rect[3]))
# ------------------------------------------------------------------ #
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 02830c85..ab6fde19 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -13,13 +13,12 @@ from io import BytesIO
from typing import Any, Callable, Literal
import numpy as np
-
-from ..types import BBox
import pypdfium2 as pdfium
from loguru import logger
from PIL import Image, ImageOps
from ..data.data_reader_writer import FileBasedDataWriter
+from ..types import BBox
from .bbox_utils import normalize_to_int_bbox
from .check_sys_env import is_windows_environment
from .enum_class import ImageType
@@ -66,9 +65,7 @@ def pdf_page_to_image(
dict: {'img_base64': str, 'img_pil': pil_img, 'scale': float }
"""
pil_img, scale = page_to_image(page, dpi=dpi)
- image_dict = {
- "scale": scale,
- }
+ image_dict: dict[str, Any] = {"scale": scale}
if image_type == ImageType.BASE64:
try:
image_dict["img_base64"] = image_to_b64str(pil_img)
@@ -515,9 +512,7 @@ def get_crop_img(bbox: BBox, pil_img: Image.Image, scale: float = 2.0) -> Image.
return pil_img.crop(tuple(scale_bbox))
-def get_crop_np_img(
- bbox: BBox, input_img: Image.Image | np.ndarray, scale: float = 2.0
-) -> np.ndarray:
+def get_crop_np_img(bbox: BBox, input_img: Image.Image | np.ndarray, scale: float = 2.0) -> np.ndarray:
if isinstance(input_img, Image.Image):
np_img = np.asarray(input_img)
elif isinstance(input_img, np.ndarray):