Skip to content

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

refactor: add type hints to all backend/pipeline/ functions

jinzhenj132e4c9e8cc6
diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.py
index 12738f46..3c05859d 100644
--- a/mineru/backend/pipeline/model_init.py
+++ b/mineru/backend/pipeline/model_init.py
@@ -5,18 +5,18 @@ import threading
import torch
from loguru import logger
-from .model_list import AtomicModel
from ...model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
-from ...model.mfr.unimernet.Unimernet import UnimernetModel
from ...model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
-from mineru.model.ocr.pytorch_paddle import PytorchPaddleOCR
-from ...model.table.cls.paddle_table_cls import PaddleTableClsModel
+from ...model.mfr.unimernet.Unimernet import UnimernetModel
+from ...model.ocr.pytorch_paddle import PytorchPaddleOCR
from ...model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel
+from ...model.table.cls.paddle_table_cls import PaddleTableClsModel
from ...model.table.rec.slanet_plus.main import PaddleTableModel
from ...model.table.rec.unet_table.main import UnetTableModel
from ...utils.config_reader import get_device
from ...utils.enum_class import ModelPath
from ...utils.models_download_utils import auto_download_and_get_model_root_path
+from .model_list import AtomicModel
PIPELINE_MODEL_INIT_LOCK = threading.RLock()
# 这些锁保护 pipeline 与 hybrid 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
@@ -25,9 +25,7 @@ PIPELINE_MFR_INFERENCE_LOCK = threading.RLock()
PIPELINE_OCR_DET_INFERENCE_LOCK = threading.RLock()
PIPELINE_OCR_REC_INFERENCE_LOCK = threading.RLock()
# 临时关闭 pipeline/hybrid 共享推理阶段锁;需要回滚实验时可通过环境变量重新打开。
-PIPELINE_INFERENCE_LOCKS_ENABLED = os.getenv(
- 'MINERU_ENABLE_PIPELINE_INFERENCE_LOCKS', 'False'
-).lower() in ['true', '1', 'yes']
+PIPELINE_INFERENCE_LOCKS_ENABLED = os.getenv("MINERU_ENABLE_PIPELINE_INFERENCE_LOCKS", "False").lower() in ["true", "1", "yes"]
def _run_with_inference_lock(inference_lock, inference_callable, *args, **kwargs):
@@ -41,35 +39,28 @@ def _run_with_inference_lock(inference_lock, inference_callable, *args, **kwargs
def run_layout_inference(inference_callable, *args, **kwargs):
"""按实验开关执行共享 Layout 模型调用。"""
- return _run_with_inference_lock(
- PIPELINE_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs
- )
+ return _run_with_inference_lock(PIPELINE_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs)
def run_mfr_inference(inference_callable, *args, **kwargs):
"""按实验开关执行共享 MFR 模型调用。"""
- return _run_with_inference_lock(
- PIPELINE_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs
- )
+ return _run_with_inference_lock(PIPELINE_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
def run_ocr_det_inference(inference_callable, *args, **kwargs):
"""按实验开关执行共享 OCR det 模型调用。"""
- return _run_with_inference_lock(
- PIPELINE_OCR_DET_INFERENCE_LOCK, inference_callable, *args, **kwargs
- )
+ return _run_with_inference_lock(PIPELINE_OCR_DET_INFERENCE_LOCK, inference_callable, *args, **kwargs)
def run_ocr_rec_inference(inference_callable, *args, **kwargs):
"""按实验开关执行共享 OCR rec 模型调用。"""
- return _run_with_inference_lock(
- PIPELINE_OCR_REC_INFERENCE_LOCK, inference_callable, *args, **kwargs
- )
+ return _run_with_inference_lock(PIPELINE_OCR_REC_INFERENCE_LOCK, inference_callable, *args, **kwargs)
+
-MFR_MODEL = os.getenv('MINERU_FORMULA_CH_SUPPORT', 'False')
-if MFR_MODEL.lower() in ['true', '1', 'yes']:
+MFR_MODEL = os.getenv("MINERU_FORMULA_CH_SUPPORT", "False")
+if MFR_MODEL.lower() in ["true", "1", "yes"]:
MFR_MODEL = "pp_formulanet_plus_m"
-elif MFR_MODEL.lower() in ['false', '0', 'no']:
+elif MFR_MODEL.lower() in ["false", "0", "no"]:
MFR_MODEL = "unimernet_small"
else:
logger.warning(f"Invalid MINERU_FORMULA_CH_SUPPORT value: {MFR_MODEL}, set to default 'False'")
@@ -83,7 +74,7 @@ def table_orientation_cls_model_init():
det_db_box_thresh=0.5,
det_db_unclip_ratio=1.6,
lang="ch_lite",
- enable_merge_det_boxes=False
+ enable_merge_det_boxes=False,
)
cls_model = MineruTableOrientationClsModel(ocr_engine)
return cls_model
@@ -93,54 +84,43 @@ def table_cls_model_init():
return PaddleTableClsModel()
-def wired_table_model_init(lang=None):
+def wired_table_model_init(lang: str | None = None) -> Any:
atom_model_manager = AtomModelSingleton()
ocr_engine = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- det_db_box_thresh=0.5,
- det_db_unclip_ratio=1.6,
- lang=lang,
- enable_merge_det_boxes=False
+ atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False
)
table_model = UnetTableModel(ocr_engine)
return table_model
-def wireless_table_model_init(lang=None):
+def wireless_table_model_init(lang: str | None = None) -> Any:
atom_model_manager = AtomModelSingleton()
ocr_engine = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- det_db_box_thresh=0.5,
- det_db_unclip_ratio=1.6,
- lang=lang,
- enable_merge_det_boxes=False
+ atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False
)
table_model = PaddleTableModel(ocr_engine)
return table_model
-def mfr_model_init(weight_dir, device='cpu'):
+def mfr_model_init(weight_dir: str, device: str = "cpu") -> Any:
if MFR_MODEL == "unimernet_small":
mfr_model = UnimernetModel(weight_dir, device)
elif MFR_MODEL == "pp_formulanet_plus_m":
mfr_model = FormulaRecognizer(weight_dir, device)
else:
- logger.error('MFR model name not allow')
+ logger.error("MFR model name not allow")
exit(1)
return mfr_model
-def pp_doclayout_v2_model_init(weight, device='cpu'):
- if str(device).startswith('npu'):
+def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> Any:
+ if str(device).startswith("npu"):
device = torch.device(device)
model = PPDocLayoutV2LayoutModel(weight, device)
return model
-def ocr_model_init(det_db_box_thresh=0.5,
- lang=None,
- det_db_unclip_ratio=1.5,
- enable_merge_det_boxes=True
- ):
+
+def ocr_model_init(det_db_box_thresh: float = 0.5, lang: str | None = None, det_db_unclip_ratio: float = 1.5, enable_merge_det_boxes: bool = True) -> Any:
if lang in [None, "ch"]:
use_dilation = True
@@ -148,7 +128,7 @@ def ocr_model_init(det_db_box_thresh=0.5,
else:
use_dilation = False
- if lang is not None and lang != '':
+ if lang is not None and lang != "":
model = PytorchPaddleOCR(
det_db_box_thresh=det_db_box_thresh,
lang=lang,
@@ -179,25 +159,22 @@ class AtomModelSingleton:
def get_atom_model(self, atom_model_name: str, **kwargs):
- lang = kwargs.get('lang', None)
+ lang = kwargs.get("lang", None)
if atom_model_name in [AtomicModel.WiredTable, AtomicModel.WirelessTable]:
- key = (
- atom_model_name,
- lang
- )
+ key = (atom_model_name, lang)
elif atom_model_name in [AtomicModel.OCR]:
key = (
atom_model_name,
- kwargs.get('det_db_box_thresh', 0.5),
+ kwargs.get("det_db_box_thresh", 0.5),
lang,
- kwargs.get('det_db_unclip_ratio', 1.5),
- kwargs.get('enable_merge_det_boxes', True)
+ kwargs.get("det_db_unclip_ratio", 1.5),
+ kwargs.get("enable_merge_det_boxes", True),
)
elif atom_model_name in [AtomicModel.Layout, AtomicModel.MFR]:
key = (
atom_model_name,
- kwargs.get('device'),
+ kwargs.get("device"),
)
else:
key = atom_model_name
@@ -207,43 +184,38 @@ class AtomModelSingleton:
self._models[key] = atom_model_init(model_name=atom_model_name, **kwargs)
return self._models[key]
-def atom_model_init(model_name: str, **kwargs):
+
+def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = None
if model_name == AtomicModel.Layout:
- atom_model = pp_doclayout_v2_model_init(
- kwargs.get('pp_doclayout_v2_weights'),
- kwargs.get('device')
- )
+ atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))
elif model_name == AtomicModel.MFR:
- atom_model = mfr_model_init(
- kwargs.get('mfr_weight_dir'),
- kwargs.get('device')
- )
+ atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))
elif model_name == AtomicModel.OCR:
atom_model = ocr_model_init(
- kwargs.get('det_db_box_thresh', 0.5),
- kwargs.get('lang'),
- kwargs.get('det_db_unclip_ratio', 1.5),
- kwargs.get('enable_merge_det_boxes', True)
+ kwargs.get("det_db_box_thresh", 0.5),
+ kwargs.get("lang"),
+ kwargs.get("det_db_unclip_ratio", 1.5),
+ kwargs.get("enable_merge_det_boxes", True),
)
elif model_name == AtomicModel.WirelessTable:
atom_model = wireless_table_model_init(
- kwargs.get('lang'),
+ kwargs.get("lang"),
)
elif model_name == AtomicModel.WiredTable:
atom_model = wired_table_model_init(
- kwargs.get('lang'),
+ kwargs.get("lang"),
)
elif model_name == AtomicModel.TableCls:
atom_model = table_cls_model_init()
elif model_name == AtomicModel.TableOrientationCls:
atom_model = table_orientation_cls_model_init()
else:
- logger.error('model name not allow')
+ logger.error("model name not allow")
exit(1)
if atom_model is None:
- logger.error('model init failed')
+ logger.error("model init failed")
exit(1)
else:
return atom_model
@@ -251,15 +223,13 @@ def atom_model_init(model_name: str, **kwargs):
class MineruPipelineModel:
def __init__(self, **kwargs):
- self.formula_config = kwargs.get('formula_config')
- self.apply_formula = self.formula_config.get('enable', True)
- self.table_config = kwargs.get('table_config')
- self.apply_table = self.table_config.get('enable', True)
- self.lang = kwargs.get('lang', None)
- self.device = kwargs.get('device', 'cpu')
- logger.info(
- 'DocAnalysis init, this may take some times......'
- )
+ self.formula_config = kwargs.get("formula_config")
+ self.apply_formula = self.formula_config.get("enable", True)
+ self.table_config = kwargs.get("table_config")
+ self.apply_table = self.table_config.get("enable", True)
+ self.lang = kwargs.get("lang", None)
+ self.device = kwargs.get("device", "cpu")
+ logger.info("DocAnalysis init, this may take some times......")
atom_model_manager = AtomModelSingleton()
if self.apply_formula:
@@ -269,7 +239,7 @@ class MineruPipelineModel:
elif MFR_MODEL == "pp_formulanet_plus_m":
mfr_model_path = ModelPath.pp_formulanet_plus_m
else:
- logger.error('MFR model name not allow')
+ logger.error("MFR model name not allow")
exit(1)
self.mfr_model = atom_model_manager.get_atom_model(
@@ -287,10 +257,7 @@ class MineruPipelineModel:
device=self.device,
)
# 初始化ocr
- self.ocr_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang=self.lang
- )
+ self.ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=self.lang)
# init table model
if self.apply_table:
self.wired_table_model = atom_model_manager.get_atom_model(
@@ -309,7 +276,7 @@ class MineruPipelineModel:
lang=self.lang,
)
- logger.info('DocAnalysis init done!')
+ logger.info("DocAnalysis init done!")
class HybridModelSingleton:
@@ -337,9 +304,11 @@ class HybridModelSingleton:
)
return self._models[key]
+
def ocr_det_batch_setting():
import torch
from packaging import version
+
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
if device_type.lower() in ["corex"]:
enable_ocr_det_batch = False
@@ -350,12 +319,13 @@ def ocr_det_batch_setting():
return enable_ocr_det_batch
+
class MineruHybridModel:
def __init__(
- self,
- device=None,
- lang=None,
- formula_enable=True,
+ self,
+ device=None,
+ lang=None,
+ formula_enable=True,
):
if device is not None:
self.device = device
@@ -366,9 +336,10 @@ class MineruHybridModel:
self.enable_ocr_det_batch = ocr_det_batch_setting()
- if str(self.device).startswith('npu'):
+ if str(self.device).startswith("npu"):
try:
import torch_npu
+
if torch_npu.npu.is_available():
torch_npu.npu.set_compile_mode(jit_compile=False)
except Exception as e:
@@ -380,10 +351,7 @@ class MineruHybridModel:
self.atom_model_manager = AtomModelSingleton()
# 初始化OCR模型
- self.ocr_model = self.atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang=self.lang
- )
+ self.ocr_model = self.atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=self.lang)
# 初始化layout模型,用于提供行内公式检测框和Hybrid标题拆分
self.layout_model = self.atom_model_manager.get_atom_model(
@@ -404,7 +372,7 @@ class MineruHybridModel:
elif MFR_MODEL == "pp_formulanet_plus_m":
mfr_model_path = ModelPath.pp_formulanet_plus_m
else:
- logger.error('MFR model name not allow')
+ logger.error("MFR model name not allow")
exit(1)
self.mfr_model = self.atom_model_manager.get_atom_model(
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 4bccf095..7b0cb542 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -48,22 +48,22 @@ def blocks_to_page_info(
return page_info
-def build_page_model_info(page_layout_dets, page_index, pil_img):
+def build_page_model_info(page_layout_dets: list, page_index: int, pil_img: Any) -> dict:
page_info_dict = {"page_no": page_index, "width": pil_img.width, "height": pil_img.height}
return {"layout_dets": page_layout_dets, "page_info": page_info_dict}
def append_batch_results_to_middle_json(
- middle_json,
- batch_results,
- images_list,
- pdf_doc,
- image_writer,
- page_start_index=0,
- ocr_enable=False,
- model_list=None,
- progress_bar=None,
-):
+ middle_json: dict,
+ batch_results: list,
+ images_list: list,
+ pdf_doc: Any,
+ image_writer: Any,
+ page_start_index: int = 0,
+ ocr_enable: bool = False,
+ model_list: list | None = None,
+ progress_bar: Any = None,
+) -> None:
page_model_infos = []
for offset, (image_dict, page_layout_dets) in enumerate(zip(images_list, batch_results)):
page_index = page_start_index + offset
@@ -88,7 +88,7 @@ def append_batch_results_to_middle_json(
)
-def _extract_text_from_block(block):
+def _extract_text_from_block(block: Block) -> str:
text_parts = []
for line in block.get("lines", []):
for span in line.get("spans", []):
@@ -97,7 +97,7 @@ def _extract_text_from_block(block):
return "".join(text_parts).strip()
-def _normalize_formula_tag_content(tag_content):
+def _normalize_formula_tag_content(tag_content: str) -> str:
tag_content = full_to_half(tag_content.strip())
if tag_content.startswith("("):
tag_content = tag_content[1:].strip()
@@ -106,7 +106,7 @@ def _normalize_formula_tag_content(tag_content):
return tag_content
-def _get_interline_equation_span(block):
+def _get_interline_equation_span(block: Block) -> Span | None:
for line in block.get("lines", []):
for span in line.get("spans", []):
if span.get("type") == ContentType.INTERLINE_EQUATION:
@@ -114,7 +114,7 @@ def _get_interline_equation_span(block):
return None
-def _append_formula_number_tag(equation_block, formula_number_block):
+def _append_formula_number_tag(equation_block: Block, formula_number_block: Block) -> None:
equation_span = _get_interline_equation_span(equation_block)
tag_content = _normalize_formula_tag_content(_extract_text_from_block(formula_number_block))
if equation_span is not None:
@@ -122,7 +122,7 @@ def _append_formula_number_tag(equation_block, formula_number_block):
equation_span["content"] = f"{formula}\\tag{{{tag_content}}}"
-def _optimize_formula_number_blocks(pdf_info_list):
+def _optimize_formula_number_blocks(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
optimized_blocks = []
blocks = page_info.get("preproc_blocks", [])
@@ -152,7 +152,7 @@ def _optimize_formula_number_blocks(pdf_info_list):
page_info["preproc_blocks"] = optimized_blocks
-def _apply_post_ocr(pdf_info_list, lang=None):
+def _apply_post_ocr(pdf_info_list: list[PageInfo], lang: str | None = None) -> None:
from mineru.backend.utils.middle_json_utils import apply_post_ocr
atom_model_manager = AtomModelSingleton()
@@ -164,7 +164,7 @@ def _apply_post_ocr(pdf_info_list, lang=None):
apply_post_ocr(pdf_info_list, ocr_model)
-def _post_block_process(pdf_info_list):
+def _post_block_process(pdf_info_list: list[PageInfo]) -> None:
for page_info in pdf_info_list:
for block_key in ["preproc_blocks", "para_blocks"]:
for block in page_info.get(block_key, []):
@@ -179,12 +179,12 @@ def _post_block_process(pdf_info_list):
block["type"] = BlockType.TEXT
-def apply_server_side_postprocess(pdf_info_list, lang=None):
+def apply_server_side_postprocess(pdf_info_list: list[PageInfo], lang: str | None = None) -> None:
"""执行只能在服务端完成的后处理;目前仅包含依赖 OCR 模型的 post-OCR。"""
_apply_post_ocr(pdf_info_list, lang=lang)
-def finalize_middle_json_from_preproc(pdf_info_list):
+def finalize_middle_json_from_preproc(pdf_info_list: list[PageInfo]) -> None:
"""从 preproc_blocks 执行确定性 finalize,供服务端完整路径和客户端复用。"""
_optimize_formula_number_blocks(pdf_info_list)
para_split(pdf_info_list)
@@ -194,19 +194,19 @@ def finalize_middle_json_from_preproc(pdf_info_list):
def finalize_middle_json(
- pdf_info_list,
- lang=None,
-):
+ pdf_info_list: list[PageInfo],
+ lang: str | None = None,
+) -> None:
"""Apply document-level post processing once all page_info entries are ready."""
apply_server_side_postprocess(pdf_info_list, lang=lang)
finalize_middle_json_from_preproc(pdf_info_list)
-def init_middle_json():
+def init_middle_json() -> dict:
return {"pdf_info": [], "_backend": "pipeline", "_version_name": __version__}
-def result_to_middle_json(model_list, images_list, pdf_doc, image_writer, lang=None, ocr_enable=False, formula_enable=None):
+def result_to_middle_json(model_list: list, images_list: list, pdf_doc: Any, image_writer: Any, lang: str | None = None, ocr_enable: bool = False, formula_enable: bool | None = None) -> dict:
from mineru.backend.utils.middle_json_utils import build_middle_json
return build_middle_json(
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index f7bc6a9f..9ae41771 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -4,31 +4,27 @@ import time
from typing import List, Tuple
import pypdfium2 as pdfium
-from PIL import Image
from loguru import logger
+from PIL import Image
from tqdm import tqdm
-from .model_init import MineruPipelineModel, PIPELINE_MODEL_INIT_LOCK
+from ...utils.config_reader import get_device, get_processing_window_size
+from ...utils.enum_class import ImageType
+from ...utils.model_utils import clean_memory, get_vram
+from ...utils.pdf_classify import classify
+from ...utils.pdf_image_tools import load_images_from_pdf_doc
+from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ..utils.runtime_utils import exclude_progress_bar_idle_time
+from .model_init import PIPELINE_MODEL_INIT_LOCK, MineruPipelineModel
from .model_output_to_middle_json import (
- apply_server_side_postprocess,
append_batch_results_to_middle_json,
+ apply_server_side_postprocess,
finalize_middle_json,
init_middle_json,
)
-from ..utils.runtime_utils import exclude_progress_bar_idle_time
-from mineru.utils.config_reader import get_device, get_processing_window_size
-from ...utils.enum_class import ImageType
-from ...utils.pdf_classify import classify
-from ...utils.pdf_image_tools import load_images_from_pdf_doc
-from ...utils.model_utils import get_vram, clean_memory
-from ...utils.pdfium_guard import (
- close_pdfium_document,
- get_pdfium_document_page_count,
- open_pdfium_document,
-)
+os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # 让mps可以fallback
-os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 让mps可以fallback
class ModelSingleton:
_instance = None
@@ -71,31 +67,31 @@ def custom_model_init(
table_config = {"enable": table_enable}
model_input = {
- 'device': device,
- 'table_config': table_config,
- 'formula_config': formula_config,
- 'lang': lang,
+ "device": device,
+ "table_config": table_config,
+ "formula_config": formula_config,
+ "lang": lang,
}
custom_model = MineruPipelineModel(**model_input)
model_init_cost = time.time() - model_init_start
- logger.info(f'model init cost: {model_init_cost}')
+ logger.info(f"model init cost: {model_init_cost}")
return custom_model
def _get_ocr_enable(pdf_bytes, parse_method: str) -> bool:
- if parse_method == 'auto':
- return classify(pdf_bytes) == 'ocr'
- if parse_method == 'ocr':
+ if parse_method == "auto":
+ return classify(pdf_bytes) == "ocr"
+ if parse_method == "ocr":
return True
return False
def _close_images(images_list):
for image_dict in images_list or []:
- pil_img = image_dict.get('img_pil')
+ pil_img = image_dict.get("img_pil")
if pil_img is not None:
try:
pil_img.close()
@@ -104,10 +100,7 @@ def _close_images(images_list):
def _format_doc_slices(batch_slices):
- return ",".join(
- f"doc{item['doc_index']}:{item['page_start'] + 1}-{item['page_end'] + 1}"
- for item in batch_slices
- )
+ return ",".join(f"doc{item['doc_index']}:{item['page_start'] + 1}-{item['page_end'] + 1}" for item in batch_slices)
def _finalize_processing_window_context(
@@ -115,29 +108,27 @@ def _finalize_processing_window_context(
on_doc_ready,
client_side_output_generation=False,
):
- if context['closed']:
+ if context["closed"]:
return
if client_side_output_generation:
apply_server_side_postprocess(
- context['middle_json']['pdf_info'],
- lang=context['lang'],
+ context["middle_json"]["pdf_info"],
+ lang=context["lang"],
)
else:
finalize_middle_json(
- context['middle_json']['pdf_info'],
- lang=context['lang'],
+ context["middle_json"]["pdf_info"],
+ lang=context["lang"],
)
- logger.debug(
- f"Pipeline doc ready: doc{context['doc_index']} pages={context['page_count']}"
- )
+ logger.debug(f"Pipeline doc ready: doc{context['doc_index']} pages={context['page_count']}")
on_doc_ready(
- context['doc_index'],
- context['model_list'],
- context['middle_json'],
- context['ocr_enable'],
+ context["doc_index"],
+ context["model_list"],
+ context["middle_json"],
+ context["ocr_enable"],
)
- close_pdfium_document(context['pdf_doc'])
- context['closed'] = True
+ close_pdfium_document(context["pdf_doc"])
+ context["closed"] = True
def _emit_zero_page_contexts(
@@ -146,7 +137,7 @@ def _emit_zero_page_contexts(
client_side_output_generation=False,
):
for context in doc_contexts:
- if context['page_count'] == 0 and not context['closed']:
+ if context["page_count"] == 0 and not context["closed"]:
_finalize_processing_window_context(
context,
on_doc_ready,
@@ -155,14 +146,14 @@ def _emit_zero_page_contexts(
def doc_analyze_streaming(
- pdf_bytes_list,
- image_writer_list,
- lang_list,
- on_doc_ready,
- parse_method: str = 'auto',
- formula_enable=True,
- table_enable=True,
- client_side_output_generation=False,
+ pdf_bytes_list,
+ image_writer_list,
+ lang_list,
+ on_doc_ready,
+ parse_method: str = "auto",
+ formula_enable=True,
+ table_enable=True,
+ client_side_output_generation=False,
):
if not (len(pdf_bytes_list) == len(image_writer_list) == len(lang_list)):
raise ValueError("pdf_bytes_list, image_writer_list, and lang_list must have the same length")
@@ -170,25 +161,23 @@ def doc_analyze_streaming(
doc_contexts = []
try:
total_pages = 0
- for doc_index, (pdf_bytes, image_writer, lang) in enumerate(
- zip(pdf_bytes_list, image_writer_list, lang_list)
- ):
+ for doc_index, (pdf_bytes, image_writer, lang) in enumerate(zip(pdf_bytes_list, image_writer_list, lang_list)):
_ocr_enable = _get_ocr_enable(pdf_bytes, parse_method)
pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
try:
page_count = get_pdfium_document_page_count(pdf_doc)
context = {
- 'doc_index': doc_index,
- 'pdf_bytes': pdf_bytes,
- 'pdf_doc': pdf_doc,
- 'page_count': page_count,
- 'next_page_idx': 0,
- 'middle_json': init_middle_json(),
- 'model_list': [],
- 'image_writer': image_writer,
- 'lang': lang,
- 'ocr_enable': _ocr_enable,
- 'closed': False,
+ "doc_index": doc_index,
+ "pdf_bytes": pdf_bytes,
+ "pdf_doc": pdf_doc,
+ "page_count": page_count,
+ "next_page_idx": 0,
+ "middle_json": init_middle_json(),
+ "model_list": [],
+ "image_writer": image_writer,
+ "lang": lang,
+ "ocr_enable": _ocr_enable,
+ "closed": False,
}
except Exception:
close_pdfium_document(pdf_doc)
@@ -207,8 +196,8 @@ def doc_analyze_streaming(
window_size = get_processing_window_size(default=64)
total_batches = (total_pages + window_size - 1) // window_size
logger.info(
- f'Pipeline processing-window multi-file run. doc_count={len(doc_contexts)}, '
- f'total_pages={total_pages}, window_size={window_size}, total_batches={total_batches}'
+ f"Pipeline processing-window multi-file run. doc_count={len(doc_contexts)}, "
+ f"total_pages={total_pages}, window_size={window_size}, total_batches={total_batches}"
)
_emit_zero_page_contexts(
@@ -232,39 +221,38 @@ def doc_analyze_streaming(
for context in doc_contexts:
if batch_capacity == 0:
break
- page_start = context['next_page_idx']
- if page_start >= context['page_count']:
+ page_start = context["next_page_idx"]
+ if page_start >= context["page_count"]:
continue
- take_count = min(batch_capacity, context['page_count'] - page_start)
+ take_count = min(batch_capacity, context["page_count"] - page_start)
page_end = page_start + take_count - 1
images_list = load_images_from_pdf_doc(
- context['pdf_doc'],
+ context["pdf_doc"],
start_page_id=page_start,
end_page_id=page_end,
image_type=ImageType.PIL,
- pdf_bytes=context['pdf_bytes'],
+ pdf_bytes=context["pdf_bytes"],
)
images_with_extra_info = [
- (image_dict['img_pil'], context['ocr_enable'], context['lang'])
- for image_dict in images_list
+ (image_dict["img_pil"], context["ocr_enable"], context["lang"]) for image_dict in images_list
]
batch_images.extend(images_with_extra_info)
batch_slices.append(
{
- 'doc_index': context['doc_index'],
- 'page_start': page_start,
- 'page_end': page_end,
- 'count': take_count,
+ "doc_index": context["doc_index"],
+ "page_start": page_start,
+ "page_end": page_end,
+ "count": take_count,
}
)
batch_payloads.append((context, images_list, page_start, take_count))
- context['next_page_idx'] = page_end + 1
+ context["next_page_idx"] = page_end + 1
batch_capacity -= take_count
logger.info(
- f'Pipeline processing window batch {batch_index}/{total_batches}: '
- f'{processed_pages + len(batch_images)}/{total_pages} pages, '
- f'batch_pages={len(batch_images)}, doc_slices={_format_doc_slices(batch_slices)}'
+ f"Pipeline processing window batch {batch_index}/{total_batches}: "
+ f"{processed_pages + len(batch_images)}/{total_pages} pages, "
+ f"batch_pages={len(batch_images)}, doc_slices={_format_doc_slices(batch_slices)}"
)
try:
@@ -284,21 +272,21 @@ def doc_analyze_streaming(
result_offset = 0
for context, images_list, page_start, take_count in batch_payloads:
- result_slice = batch_results[result_offset: result_offset + take_count]
+ result_slice = batch_results[result_offset : result_offset + take_count]
append_batch_results_to_middle_json(
- context['middle_json'],
+ context["middle_json"],
result_slice,
images_list,
- context['pdf_doc'],
- context['image_writer'],
+ context["pdf_doc"],
+ context["image_writer"],
page_start_index=page_start,
- ocr_enable=context['ocr_enable'],
- model_list=context['model_list'],
+ ocr_enable=context["ocr_enable"],
+ model_list=context["model_list"],
progress_bar=progress_bar,
)
result_offset += take_count
- if context['next_page_idx'] >= context['page_count'] and not context['closed']:
+ if context["next_page_idx"] >= context["page_count"] and not context["closed"]:
_finalize_processing_window_context(
context,
on_doc_ready,
@@ -323,15 +311,12 @@ def doc_analyze_streaming(
)
finally:
for context in doc_contexts:
- if not context['closed']:
- close_pdfium_document(context['pdf_doc'])
- context['closed'] = True
+ if not context["closed"]:
+ close_pdfium_document(context["pdf_doc"])
+ context["closed"] = True
-def batch_image_analyze(
- images_with_extra_info: List[Tuple[Image.Image, bool, str]],
- formula_enable=True,
- table_enable=True):
+def batch_image_analyze(images_with_extra_info: List[Tuple[Image.Image, bool, str]], formula_enable=True, table_enable=True):
from .batch_analyze import BatchAnalyze
@@ -339,9 +324,10 @@ def batch_image_analyze(
device = get_device()
- if str(device).startswith('npu'):
+ if str(device).startswith("npu"):
try:
import torch_npu
+
if torch_npu.npu.is_available():
torch_npu.npu.set_compile_mode(jit_compile=False)
except Exception as e:
@@ -361,13 +347,12 @@ def batch_image_analyze(
batch_ratio = 2
else:
batch_ratio = 1
- logger.info(
- f'GPU Memory: {gpu_memory} GB, Batch Ratio: {batch_ratio}. '
- )
+ logger.info(f"GPU Memory: {gpu_memory} GB, Batch Ratio: {batch_ratio}. ")
# 检测torch的版本号
import torch
from packaging import version
+
device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
if device_type.lower() in ["corex"]:
enable_ocr_det_batch = False
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index c5193e92..3e718c10 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -1,25 +1,26 @@
# Copyright (c) Opendatalab. All rights reserved.
-from mineru.backend.pipeline.para_split import ListLineTag
-from mineru.backend.pipeline.pipeline_middle_json_mkcontent import _merge_para_text
-from mineru.utils.boxbase import (
- calculate_overlap_area_2_minbox_area_ratio,
- calculate_overlap_area_in_bbox1_area_ratio,
+from ...types import Block, Line, Span
+from ...utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
+from ...utils.enum_class import BlockType, ContentType
+from ...utils.guess_suffix_or_lang import guess_language_by_text
+from ...utils.span_block_fix import (
+ is_vertical_text_block_by_spans,
+ line_sort_spans_by_left_to_right,
+ merge_spans_to_line,
+ merge_spans_to_vertical_line,
+ vertical_line_sort_spans_from_top_to_bottom,
)
-from mineru.utils.enum_class import ContentType, BlockType
-from mineru.utils.guess_suffix_or_lang import guess_language_by_text
-from mineru.types import Block, Line, Span
-from mineru.utils.span_block_fix import merge_spans_to_vertical_line, vertical_line_sort_spans_from_top_to_bottom, \
- merge_spans_to_line, line_sort_spans_by_left_to_right, is_vertical_text_block_by_spans
-from mineru.utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
-from mineru.utils.visual_magic_model_utils import (
+from ...utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
+from ...utils.visual_magic_model_utils import (
fallback_inline_caption_fragments,
fallback_leading_table_continuation_captions,
find_best_visual_parent,
)
+from .para_split import ListLineTag
+from .pipeline_middle_json_mkcontent import _merge_para_text
class MagicModel:
-
PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES = {
"abstract": BlockType.ABSTRACT,
"algorithm": BlockType.CODE,
@@ -68,7 +69,7 @@ class MagicModel:
"body": BlockType.CODE_BODY,
"caption": BlockType.CODE_CAPTION,
"footnote": BlockType.CODE_FOOTNOTE,
- }
+ },
}
def __init__(
@@ -105,12 +106,12 @@ class MagicModel:
)
self.page_text_inline_formula_spans = self.page_inline_formula + self.page_ocr_res
- for layout_det in self.__page_model_info['layout_dets']:
- if layout_det.get('label') in self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES:
- block_bbox = layout_det['bbox']
- block_type = self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES[layout_det['label']]
- block_index = layout_det['index']
- block_score = layout_det['score']
+ for layout_det in self.__page_model_info["layout_dets"]:
+ if layout_det.get("label") in self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES:
+ block_bbox = layout_det["bbox"]
+ block_type = self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES[layout_det["label"]]
+ block_index = layout_det["index"]
+ block_score = layout_det["score"]
block = self.__copy_block_fields(
layout_det,
type=block_type,
@@ -129,58 +130,45 @@ class MagicModel:
self.__classify_visual_blocks()
self.__build_return_blocks()
-
@staticmethod
def __fix_text_block(block):
- if (
- block["type"] == BlockType.TEXT
- and is_vertical_text_block_by_spans(block["spans"])
- ):
+ if block["type"] == BlockType.TEXT and is_vertical_text_block_by_spans(block["spans"]):
# layout 偶发会把竖排正文识别为横排 text,这里用旧版 span 高宽比规则兜底。
block["type"] = BlockType.VERTICAL_TEXT
if block["type"] == BlockType.VERTICAL_TEXT:
# 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block['spans'])
+ block_lines = merge_spans_to_vertical_line(block["spans"])
sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)
else:
- block_lines = merge_spans_to_line(block['spans'])
+ block_lines = merge_spans_to_line(block["spans"])
sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
if block["type"] == BlockType.CODE:
for line in sort_block_lines:
line[ListLineTag.IS_LIST_START_LINE] = True
- code_content = _merge_para_text(
- {'lines': sort_block_lines},
- False,
- '\n'
- )
+ code_content = _merge_para_text({"lines": sort_block_lines}, False, "\n")
guess_lang = guess_language_by_text(code_content)
if guess_lang not in ["txt", "unknown"]:
block["sub_type"] = "code"
block["guess_lang"] = guess_lang
- block['lines'] = sort_block_lines
- del block['spans']
+ block["lines"] = sort_block_lines
+ del block["spans"]
return block
@staticmethod
def __copy_block_fields(block, **overrides):
- extra = {k: v for k, v in block.items()
- if k not in {"cls_id", "label"} and k not in Block.__dataclass_fields__}
+ extra = {k: v for k, v in block.items() if k not in {"cls_id", "label"} and k not in Block.__dataclass_fields__}
return Block(
type=overrides.pop("type", block.get("type", "")),
bbox=overrides.pop("bbox", block.get("bbox")),
_extra={**extra, **overrides},
)
-
@staticmethod
def __is_inline_formula_block(layout_det: dict) -> bool:
- return (
- layout_det.get("label") == "inline_formula"
- or layout_det.get("cls_id") == 15
- )
+ return layout_det.get("label") == "inline_formula" or layout_det.get("cls_id") == 15
@staticmethod
def __is_ocr_text_block(layout_det: dict) -> bool:
@@ -209,7 +197,7 @@ class MagicModel:
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
BlockType.ASIDE_TEXT,
- BlockType.PAGE_FOOTNOTE
+ BlockType.PAGE_FOOTNOTE,
]:
self.discarded_blocks.append(block)
else:
@@ -298,8 +286,8 @@ class MagicModel:
def __formula_number_overlap_ratio(span, block_bbox):
"""公式编号框较窄时,沿用最小框重叠比例提高回填召回。"""
return max(
- calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox),
- calculate_overlap_area_2_minbox_area_ratio(span['bbox'], block_bbox),
+ calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block_bbox),
+ calculate_overlap_area_2_minbox_area_ratio(span["bbox"], block_bbox),
)
def __fix_axis(self):
@@ -326,21 +314,25 @@ class MagicModel:
for layout_det in layout_dets:
if self.__is_inline_formula_block(layout_det):
layout_det.pop("index", None)
- self.page_inline_formula.append(Span(
- type=ContentType.INLINE_EQUATION,
- bbox=layout_det["bbox"],
- content=layout_det["latex"],
- score=layout_det["score"],
- ))
+ self.page_inline_formula.append(
+ Span(
+ type=ContentType.INLINE_EQUATION,
+ bbox=layout_det["bbox"],
+ content=layout_det["latex"],
+ score=layout_det["score"],
+ )
+ )
continue
if self.__is_ocr_text_block(layout_det):
- self.page_ocr_res.append(Span(
- type=ContentType.TEXT,
- bbox=layout_det["bbox"],
- content=layout_det["text"],
- score=layout_det["score"],
- ))
+ self.page_ocr_res.append(
+ Span(
+ type=ContentType.TEXT,
+ bbox=layout_det["bbox"],
+ content=layout_det["text"],
+ score=layout_det["score"],
+ )
+ )
continue
if "index" in layout_det:
@@ -352,28 +344,13 @@ class MagicModel:
return
ordered_blocks = sorted(self.page_blocks, key=lambda x: x["index"])
- original_type_by_index = {
- block["index"]: block["type"] for block in ordered_blocks
- }
- position_by_index = {
- block["index"]: pos for pos, block in enumerate(ordered_blocks)
- }
- main_blocks = [
- block
- for block in ordered_blocks
- if original_type_by_index[block["index"]] in self.VISUAL_MAIN_TYPES
- ]
- child_blocks = [
- block
- for block in ordered_blocks
- if original_type_by_index[block["index"]] in self.VISUAL_CHILD_TYPES
- ]
+ original_type_by_index = {block["index"]: block["type"] for block in ordered_blocks}
+ position_by_index = {block["index"]: pos for pos, block in enumerate(ordered_blocks)}
+ main_blocks = [block for block in ordered_blocks if original_type_by_index[block["index"]] in self.VISUAL_MAIN_TYPES]
+ child_blocks = [block for block in ordered_blocks if original_type_by_index[block["index"]] in self.VISUAL_CHILD_TYPES]
child_parent_map = {}
- grouped_children = {
- main_block["index"]: {"captions": [], "footnotes": []}
- for main_block in main_blocks
- }
+ grouped_children = {main_block["index"]: {"captions": [], "footnotes": []} for main_block in main_blocks}
for child_block in child_blocks:
parent_block = self.__find_best_visual_parent(
@@ -383,9 +360,7 @@ class MagicModel:
original_type_by_index,
position_by_index,
)
- child_parent_map[child_block["index"]] = (
- None if parent_block is None else parent_block["index"]
- )
+ child_parent_map[child_block["index"]] = None if parent_block is None else parent_block["index"]
for child_block in child_blocks:
original_child_type = original_type_by_index[child_block["index"]]
@@ -486,9 +461,7 @@ class MagicModel:
main_blocks,
ordered_blocks,
position_by_index,
- main_type_to_visual_type={
- block_type: block_type for block_type in self.VISUAL_MAIN_TYPES
- },
+ main_type_to_visual_type={block_type: block_type for block_type in self.VISUAL_MAIN_TYPES},
type_by_index=original_type_by_index,
)
@@ -529,16 +502,10 @@ class MagicModel:
return self.chart_groups
def get_image_blocks(self):
- return [
- block for block in self.page_blocks if block["type"] == BlockType.IMAGE
- ]
+ return [block for block in self.page_blocks if block["type"] == BlockType.IMAGE]
def get_table_blocks(self):
- return [
- block for block in self.page_blocks if block["type"] == BlockType.TABLE
- ]
+ return [block for block in self.page_blocks if block["type"] == BlockType.TABLE]
def get_chart_blocks(self):
- return [
- block for block in self.page_blocks if block["type"] == BlockType.CHART
- ]
+ return [block for block in self.page_blocks if block["type"] == BlockType.CHART]