Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: rename RapidTable classes to PaddleTable for consistency and clarity
myhloli8851223abb23
diff --git a/README.md b/README.mdindex 0a7c7ab2..6fc3c3ca 100644--- a/README.md+++ b/README.md@@ -298,15 +298,10 @@ Currently, some models in this project are trained based on YOLO. However, since# Acknowledgments-- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)-- [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)- [UniMERNet](https://github.com/opendatalab/UniMERNet)-- [RapidTable](https://github.com/RapidAI/RapidTable)- [TableStructureRec](https://github.com/RapidAI/TableStructureRec)- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)- [PaddleOCR2Pytorch](https://github.com/frotms/PaddleOCR2Pytorch)-- [layoutreader](https://github.com/ppaanngggg/layoutreader)-- [xy-cut](https://github.com/Sanster/xy-cut)- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)- [pdftext](https://github.com/datalab-to/pdftext)diff --git a/README_zh-CN.md b/README_zh-CN.mdindex 3e9ef802..284360ab 100644--- a/README_zh-CN.md+++ b/README_zh-CN.md@@ -305,15 +305,10 @@ mineru -p <input_path> -o <output_path> -b pipeline# Acknowledgments-- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)-- [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)- [UniMERNet](https://github.com/opendatalab/UniMERNet)-- [RapidTable](https://github.com/RapidAI/RapidTable)- [TableStructureRec](https://github.com/RapidAI/TableStructureRec)- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)- [PaddleOCR2Pytorch](https://github.com/frotms/PaddleOCR2Pytorch)-- [layoutreader](https://github.com/ppaanngggg/layoutreader)-- [xy-cut](https://github.com/Sanster/xy-cut)- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)- [pdftext](https://github.com/datalab-to/pdftext)diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.pyindex de170aca..eb69ee8b 100644--- a/mineru/backend/pipeline/model_init.py+++ b/mineru/backend/pipeline/model_init.py@@ -11,7 +11,7 @@ from ...model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizerfrom mineru.model.ocr.pytorch_paddle import PytorchPaddleOCRfrom ...model.ori_cls.paddle_ori_cls import PaddleOrientationClsModelfrom ...model.table.cls.paddle_table_cls import PaddleTableClsModel-from ...model.table.rec.slanet_plus.main import RapidTableModel+from ...model.table.rec.slanet_plus.main import PaddleTableModelfrom ...model.table.rec.unet_table.main import UnetTableModelfrom ...utils.config_reader import get_devicefrom ...utils.enum_class import ModelPath@@ -66,7 +66,7 @@ def wireless_table_model_init(lang=None):lang=lang,enable_merge_det_boxes=False)- table_model = RapidTableModel(ocr_engine)+ table_model = PaddleTableModel(ocr_engine)return table_modeldiff --git a/mineru/model/reading_order/__init__.py b/mineru/model/reading_order/__init__.pydeleted file mode 100644index 1e17167c..00000000--- a/mineru/model/reading_order/__init__.py+++ /dev/null@@ -1 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.diff --git a/mineru/model/reading_order/layout_reader.py b/mineru/model/reading_order/layout_reader.pydeleted file mode 100644index dfe71a89..00000000--- a/mineru/model/reading_order/layout_reader.py+++ /dev/null@@ -1,125 +0,0 @@-from collections import defaultdict-from typing import List, Dict--import torch-from transformers import LayoutLMv3ForTokenClassification--MAX_LEN = 510-CLS_TOKEN_ID = 0-UNK_TOKEN_ID = 3-EOS_TOKEN_ID = 2---class DataCollator:- def __call__(self, features: List[dict]) -> Dict[str, torch.Tensor]:- bbox = []- labels = []- input_ids = []- attention_mask = []-- # clip bbox and labels to max length, build input_ids and attention_mask- for feature in features:- _bbox = feature["source_boxes"]- if len(_bbox) > MAX_LEN:- _bbox = _bbox[:MAX_LEN]- _labels = feature["target_index"]- if len(_labels) > MAX_LEN:- _labels = _labels[:MAX_LEN]- _input_ids = [UNK_TOKEN_ID] * len(_bbox)- _attention_mask = [1] * len(_bbox)- assert len(_bbox) == len(_labels) == len(_input_ids) == len(_attention_mask)- bbox.append(_bbox)- labels.append(_labels)- input_ids.append(_input_ids)- attention_mask.append(_attention_mask)-- # add CLS and EOS tokens- for i in range(len(bbox)):- bbox[i] = [[0, 0, 0, 0]] + bbox[i] + [[0, 0, 0, 0]]- labels[i] = [-100] + labels[i] + [-100]- input_ids[i] = [CLS_TOKEN_ID] + input_ids[i] + [EOS_TOKEN_ID]- attention_mask[i] = [1] + attention_mask[i] + [1]-- # padding to max length- max_len = max(len(x) for x in bbox)- for i in range(len(bbox)):- bbox[i] = bbox[i] + [[0, 0, 0, 0]] * (max_len - len(bbox[i]))- labels[i] = labels[i] + [-100] * (max_len - len(labels[i]))- input_ids[i] = input_ids[i] + [EOS_TOKEN_ID] * (max_len - len(input_ids[i]))- attention_mask[i] = attention_mask[i] + [0] * (- max_len - len(attention_mask[i])- )-- ret = {- "bbox": torch.tensor(bbox),- "attention_mask": torch.tensor(attention_mask),- "labels": torch.tensor(labels),- "input_ids": torch.tensor(input_ids),- }- # set label > MAX_LEN to -100, because original labels may be > MAX_LEN- ret["labels"][ret["labels"] > MAX_LEN] = -100- # set label > 0 to label-1, because original labels are 1-indexed- ret["labels"][ret["labels"] > 0] -= 1- return ret---def boxes2inputs(boxes: List[List[int]]) -> Dict[str, torch.Tensor]:- bbox = [[0, 0, 0, 0]] + boxes + [[0, 0, 0, 0]]- input_ids = [CLS_TOKEN_ID] + [UNK_TOKEN_ID] * len(boxes) + [EOS_TOKEN_ID]- attention_mask = [1] + [1] * len(boxes) + [1]- return {- "bbox": torch.tensor([bbox]),- "attention_mask": torch.tensor([attention_mask]),- "input_ids": torch.tensor([input_ids]),- }---def prepare_inputs(- inputs: Dict[str, torch.Tensor], model: LayoutLMv3ForTokenClassification-) -> Dict[str, torch.Tensor]:- ret = {}- for k, v in inputs.items():- v = v.to(model.device)- if torch.is_floating_point(v):- v = v.to(model.dtype)- ret[k] = v- return ret---def parse_logits(logits: torch.Tensor, length: int) -> List[int]:- """- parse logits to orders-- :param logits: logits from model- :param length: input length- :return: orders- """- logits = logits[1 : length + 1, :length]- orders = logits.argsort(descending=False).tolist()- ret = [o.pop() for o in orders]- while True:- order_to_idxes = defaultdict(list)- for idx, order in enumerate(ret):- order_to_idxes[order].append(idx)- # filter idxes len > 1- order_to_idxes = {k: v for k, v in order_to_idxes.items() if len(v) > 1}- if not order_to_idxes:- break- # filter- for order, idxes in order_to_idxes.items():- # find original logits of idxes- idxes_to_logit = {}- for idx in idxes:- idxes_to_logit[idx] = logits[idx, order]- idxes_to_logit = sorted(- idxes_to_logit.items(), key=lambda x: x[1], reverse=True- )- # keep the highest logit as order, set others to next candidate- for idx, _ in idxes_to_logit[1:]:- ret[idx] = orders[idx].pop()-- return ret---def check_duplicate(a: List[int]) -> bool:- return len(a) != len(set(a))diff --git a/mineru/model/reading_order/xycut.py b/mineru/model/reading_order/xycut.pydeleted file mode 100644index 7a36f527..00000000--- a/mineru/model/reading_order/xycut.py+++ /dev/null@@ -1,242 +0,0 @@-from typing import List-import cv2-import numpy as np---def projection_by_bboxes(boxes: np.array, axis: int) -> np.ndarray:- """- 通过一组 bbox 获得投影直方图,最后以 per-pixel 形式输出-- Args:- boxes: [N, 4]- axis: 0-x坐标向水平方向投影, 1-y坐标向垂直方向投影-- Returns:- 1D 投影直方图,长度为投影方向坐标的最大值(我们不需要图片的实际边长,因为只是要找文本框的间隔)-- """- assert axis in [0, 1]- length = np.max(boxes[:, axis::2])- res = np.zeros(length, dtype=int)- # TODO: how to remove for loop?- for start, end in boxes[:, axis::2]:- res[start:end] += 1- return res---# from: https://dothinking.github.io/2021-06-19-%E9%80%92%E5%BD%92%E6%8A%95%E5%BD%B1%E5%88%86%E5%89%B2%E7%AE%97%E6%B3%95/#:~:text=%E9%80%92%E5%BD%92%E6%8A%95%E5%BD%B1%E5%88%86%E5%89%B2%EF%BC%88Recursive%20XY,%EF%BC%8C%E5%8F%AF%E4%BB%A5%E5%88%92%E5%88%86%E6%AE%B5%E8%90%BD%E3%80%81%E8%A1%8C%E3%80%82-def split_projection_profile(arr_values: np.array, min_value: float, min_gap: float):- """Split projection profile:-- ```- ┌──┐- arr_values │ │ ┌─┐───- ┌──┐ │ │ │ │ |- │ │ │ │ ┌───┐ │ │min_value- │ │<- min_gap ->│ │ │ │ │ │ |- ────┴──┴─────────────┴──┴─┴───┴─┴─┴─┴───- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16- ```-- Args:- arr_values (np.array): 1-d array representing the projection profile.- min_value (float): Ignore the profile if `arr_value` is less than `min_value`.- min_gap (float): Ignore the gap if less than this value.-- Returns:- tuple: Start indexes and end indexes of split groups.- """- # all indexes with projection height exceeding the threshold- arr_index = np.where(arr_values > min_value)[0]- if not len(arr_index):- return-- # find zero intervals between adjacent projections- # | | ||- # ||||<- zero-interval -> |||||- arr_diff = arr_index[1:] - arr_index[0:-1]- arr_diff_index = np.where(arr_diff > min_gap)[0]- arr_zero_intvl_start = arr_index[arr_diff_index]- arr_zero_intvl_end = arr_index[arr_diff_index + 1]-- # convert to index of projection range:- # the start index of zero interval is the end index of projection- arr_start = np.insert(arr_zero_intvl_end, 0, arr_index[0])- arr_end = np.append(arr_zero_intvl_start, arr_index[-1])- arr_end += 1 # end index will be excluded as index slice-- return arr_start, arr_end---def recursive_xy_cut(boxes: np.ndarray, indices: List[int], res: List[int]):- """-- Args:- boxes: (N, 4)- indices: 递归过程中始终表示 box 在原始数据中的索引- res: 保存输出结果-- """- # 向 y 轴投影- assert len(boxes) == len(indices)-- _indices = boxes[:, 1].argsort()- y_sorted_boxes = boxes[_indices]- y_sorted_indices = indices[_indices]-- # debug_vis(y_sorted_boxes, y_sorted_indices)-- y_projection = projection_by_bboxes(boxes=y_sorted_boxes, axis=1)- pos_y = split_projection_profile(y_projection, 0, 1)- if not pos_y:- return-- arr_y0, arr_y1 = pos_y- for r0, r1 in zip(arr_y0, arr_y1):- # [r0, r1] 表示按照水平切分,有 bbox 的区域,对这些区域会再进行垂直切分- _indices = (r0 <= y_sorted_boxes[:, 1]) & (y_sorted_boxes[:, 1] < r1)-- y_sorted_boxes_chunk = y_sorted_boxes[_indices]- y_sorted_indices_chunk = y_sorted_indices[_indices]-- _indices = y_sorted_boxes_chunk[:, 0].argsort()- x_sorted_boxes_chunk = y_sorted_boxes_chunk[_indices]- x_sorted_indices_chunk = y_sorted_indices_chunk[_indices]-- # 往 x 方向投影- x_projection = projection_by_bboxes(boxes=x_sorted_boxes_chunk, axis=0)- pos_x = split_projection_profile(x_projection, 0, 1)- if not pos_x:- continue-- arr_x0, arr_x1 = pos_x- if len(arr_x0) == 1:- # x 方向无法切分- res.extend(x_sorted_indices_chunk)- continue-- # x 方向上能分开,继续递归调用- for c0, c1 in zip(arr_x0, arr_x1):- _indices = (c0 <= x_sorted_boxes_chunk[:, 0]) & (- x_sorted_boxes_chunk[:, 0] < c1- )- recursive_xy_cut(- x_sorted_boxes_chunk[_indices], x_sorted_indices_chunk[_indices], res- )---def points_to_bbox(points):- assert len(points) == 8-- # [x1,y1,x2,y2,x3,y3,x4,y4]- left = min(points[::2])- right = max(points[::2])- top = min(points[1::2])- bottom = max(points[1::2])-- left = max(left, 0)- top = max(top, 0)- right = max(right, 0)- bottom = max(bottom, 0)- return [left, top, right, bottom]---def bbox2points(bbox):- left, top, right, bottom = bbox- return [left, top, right, top, right, bottom, left, bottom]---def vis_polygon(img, points, thickness=2, color=None):- br2bl_color = color- tl2tr_color = color- tr2br_color = color- bl2tl_color = color- cv2.line(- img,- (points[0][0], points[0][1]),- (points[1][0], points[1][1]),- color=tl2tr_color,- thickness=thickness,- )-- cv2.line(- img,- (points[1][0], points[1][1]),- (points[2][0], points[2][1]),- color=tr2br_color,- thickness=thickness,- )-- cv2.line(- img,- (points[2][0], points[2][1]),- (points[3][0], points[3][1]),- color=br2bl_color,- thickness=thickness,- )-- cv2.line(- img,- (points[3][0], points[3][1]),- (points[0][0], points[0][1]),- color=bl2tl_color,- thickness=thickness,- )- return img---def vis_points(- img: np.ndarray, points, texts: List[str] = None, color=(0, 200, 0)-) -> np.ndarray:- """-- Args:- img:- points: [N, 8] 8: x1,y1,x2,y2,x3,y3,x3,y4- texts:- color:-- Returns:-- """- points = np.array(points)- if texts is not None:- assert len(texts) == points.shape[0]-- for i, _points in enumerate(points):- vis_polygon(img, _points.reshape(-1, 2), thickness=2, color=color)- bbox = points_to_bbox(_points)- left, top, right, bottom = bbox- cx = (left + right) // 2- cy = (top + bottom) // 2-- txt = texts[i]- font = cv2.FONT_HERSHEY_SIMPLEX- cat_size = cv2.getTextSize(txt, font, 0.5, 2)[0]-- img = cv2.rectangle(- img,- (cx - 5 * len(txt), cy - cat_size[1] - 5),- (cx - 5 * len(txt) + cat_size[0], cy - 5),- color,- -1,- )-- img = cv2.putText(- img,- txt,- (cx - 5 * len(txt), cy - 5),- font,- 0.5,- (255, 255, 255),- thickness=1,- lineType=cv2.LINE_AA,- )-- return img---def vis_polygons_with_index(image, points):- texts = [str(i) for i in range(len(points))]- res_img = vis_points(image.copy(), points, texts)- return res_img\ No newline at end of filediff --git a/mineru/model/table/rec/slanet_plus/main.py b/mineru/model/table/rec/slanet_plus/main.pyindex e02367ae..11c4d9e9 100644--- a/mineru/model/table/rec/slanet_plus/main.py+++ b/mineru/model/table/rec/slanet_plus/main.py@@ -18,7 +18,7 @@ from mineru.utils.models_download_utils import auto_download_and_get_model_root_@dataclass-class RapidTableInput:+class PaddleTableInput:model_type: Optional[str] = "slanet_plus"model_path: Union[str, Path, None, Dict[str, str]] = Noneuse_cuda: bool = False@@ -26,15 +26,15 @@ class RapidTableInput:@dataclass-class RapidTableOutput:+class PaddleTableOutput:pred_html: Optional[str] = Nonecell_bboxes: Optional[np.ndarray] = Nonelogic_points: Optional[np.ndarray] = Noneelapse: Optional[float] = None-class RapidTable:- def __init__(self, config: RapidTableInput):+class PaddleTable:+ def __init__(self, config: PaddleTableInput):self.table_structure = TableStructurer(asdict(config))self.table_matcher = TableMatch()@@ -42,7 +42,7 @@ class RapidTable:self,img: np.ndarray,ocr_result: List[Union[List[List[float]], str, str]] = None,- ) -> RapidTableOutput:+ ) -> PaddleTableOutput:if ocr_result is None:raise ValueError("OCR result is None")@@ -66,14 +66,14 @@ class RapidTable:logic_points = self.table_matcher.decode_logic_points(pred_structures)elapse = time.perf_counter() - s- return RapidTableOutput(pred_html, cell_bboxes, logic_points, elapse)+ return PaddleTableOutput(pred_html, cell_bboxes, logic_points, elapse)def batch_predict(self,images: List[np.ndarray],ocr_results: List[List[Union[List[List[float]], str, str]]],batch_size: int = 4,- ) -> List[RapidTableOutput]:+ ) -> List[PaddleTableOutput]:"""批量处理图像"""s = time.perf_counter()@@ -103,7 +103,7 @@ class RapidTable:cell_bboxes = cell_bboxes[mask]logic_points = self.table_matcher.decode_logic_points(pred_structures)- result = RapidTableOutput(pred_html, cell_bboxes, logic_points, 0)+ result = PaddleTableOutput(pred_html, cell_bboxes, logic_points, 0)output_results.append(result)total_elapse = time.perf_counter() - s@@ -149,16 +149,16 @@ def escape_html(input_string):return html.escape(input_string)-class RapidTableModel(object):+class PaddleTableModel(object):def __init__(self, ocr_engine):slanet_plus_model_path = os.path.join(auto_download_and_get_model_root_path(ModelPath.slanet_plus),ModelPath.slanet_plus,)- input_args = RapidTableInput(+ input_args = PaddleTableInput(model_type="slanet_plus", model_path=slanet_plus_model_path)- self.table_model = RapidTable(input_args)+ self.table_model = PaddleTable(input_args)self.ocr_engine = ocr_enginedef predict(self, image, ocr_result=None):diff --git a/mineru/model/table/rec/slanet_plus/table_structure_utils.py b/mineru/model/table/rec/slanet_plus/table_structure_utils.pyindex 590655d9..9a1b3b76 100644--- a/mineru/model/table/rec/slanet_plus/table_structure_utils.py+++ b/mineru/model/table/rec/slanet_plus/table_structure_utils.py@@ -33,8 +33,6 @@ from loguru import loggerclass EP(Enum):CPU_EP = "CPUExecutionProvider"- CUDA_EP = "CUDAExecutionProvider"- DIRECTML_EP = "DmlExecutionProvider"class OrtInferSession:@@ -44,9 +42,6 @@ class OrtInferSession:model_path = config.get("model_path", None)self._verify_model(model_path)- self.cfg_use_cuda = config.get("use_cuda", None)- self.cfg_use_dml = config.get("use_dml", None)-self.had_providers: List[str] = get_available_providers()EP_list = self._get_ep_list()@@ -56,7 +51,6 @@ class OrtInferSession:sess_options=sess_opt,providers=EP_list,)- self._verify_providers()@staticmethoddef _init_sess_opts(config: Dict[str, Any]) -> SessionOptions:@@ -86,126 +80,8 @@ class OrtInferSession:"arena_extend_strategy": "kSameAsRequested",}EP_list = [(EP.CPU_EP.value, cpu_provider_opts)]-- cuda_provider_opts = {- "device_id": 0,- "arena_extend_strategy": "kNextPowerOfTwo",- "cudnn_conv_algo_search": "EXHAUSTIVE",- "do_copy_in_default_stream": True,- }- self.use_cuda = self._check_cuda()- if self.use_cuda:- EP_list.insert(0, (EP.CUDA_EP.value, cuda_provider_opts))-- self.use_directml = self._check_dml()- if self.use_directml:- self.logger.info(- "Windows 10 or above detected, try to use DirectML as primary provider"- )- directml_options = (- cuda_provider_opts if self.use_cuda else cpu_provider_opts- )- EP_list.insert(0, (EP.DIRECTML_EP.value, directml_options))return EP_list- def _check_cuda(self) -> bool:- if not self.cfg_use_cuda:- return False-- cur_device = get_device()- if cur_device == "GPU" and EP.CUDA_EP.value in self.had_providers:- return True-- self.logger.warning(- "%s is not in available providers (%s). Use %s inference by default.",- EP.CUDA_EP.value,- self.had_providers,- self.had_providers[0],- )- self.logger.info("!!!Recommend to use rapidocr_paddle for inference on GPU.")- self.logger.info(- "(For reference only) If you want to use GPU acceleration, you must do:"- )- self.logger.info(- "First, uninstall all onnxruntime pakcages in current environment."- )- self.logger.info(- "Second, install onnxruntime-gpu by `pip install onnxruntime-gpu`."- )- self.logger.info(- "\tNote the onnxruntime-gpu version must match your cuda and cudnn version."- )- self.logger.info(- "\tYou can refer this link: https://onnxruntime.ai/docs/execution-providers/CUDA-EP.html"- )- self.logger.info(- "Third, ensure %s is in available providers list. e.g. ['CUDAExecutionProvider', 'CPUExecutionProvider']",- EP.CUDA_EP.value,- )- return False-- def _check_dml(self) -> bool:- if not self.cfg_use_dml:- return False-- cur_os = platform.system()- if cur_os != "Windows":- self.logger.warning(- "DirectML is only supported in Windows OS. The current OS is %s. Use %s inference by default.",- cur_os,- self.had_providers[0],- )- return False-- cur_window_version = int(platform.release().split(".")[0])- if cur_window_version < 10:- self.logger.warning(- "DirectML is only supported in Windows 10 and above OS. The current Windows version is %s. Use %s inference by default.",- cur_window_version,- self.had_providers[0],- )- return False-- if EP.DIRECTML_EP.value in self.had_providers:- return True-- self.logger.warning(- "%s is not in available providers (%s). Use %s inference by default.",- EP.DIRECTML_EP.value,- self.had_providers,- self.had_providers[0],- )- self.logger.info("If you want to use DirectML acceleration, you must do:")- self.logger.info(- "First, uninstall all onnxruntime pakcages in current environment."- )- self.logger.info(- "Second, install onnxruntime-directml by `pip install onnxruntime-directml`"- )- self.logger.info(- "Third, ensure %s is in available providers list. e.g. ['DmlExecutionProvider', 'CPUExecutionProvider']",- EP.DIRECTML_EP.value,- )- return False-- def _verify_providers(self):- session_providers = self.session.get_providers()- first_provider = session_providers[0]-- if self.use_cuda and first_provider != EP.CUDA_EP.value:- self.logger.warning(- "%s is not avaiable for current env, the inference part is automatically shifted to be executed under %s.",- EP.CUDA_EP.value,- first_provider,- )-- if self.use_directml and first_provider != EP.DIRECTML_EP.value:- self.logger.warning(- "%s is not available for current env, the inference part is automatically shifted to be executed under %s.",- EP.DIRECTML_EP.value,- first_provider,- )-def __call__(self, input_content: List[np.ndarray]) -> np.ndarray:input_dict = dict(zip(self.get_input_names(), input_content))try:diff --git a/mineru/utils/block_sort.py b/mineru/utils/block_sort.pydeleted file mode 100644index dd04e205..00000000--- a/mineru/utils/block_sort.py+++ /dev/null@@ -1,360 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-import copy-import os-import statistics-import warnings-from typing import List-import torch-from loguru import logger--from mineru.utils.config_reader import get_device-from mineru.utils.enum_class import BlockType, ModelPath-from mineru.utils.models_download_utils import auto_download_and_get_model_root_path---def sort_blocks_by_bbox(blocks, page_w, page_h, footnote_blocks):-- """获取所有line并计算正文line的高度"""- line_height = get_line_height(blocks)-- """获取所有line并对line排序"""- sorted_bboxes = sort_lines_by_model(blocks, page_w, page_h, line_height, footnote_blocks)-- """根据line的中位数算block的序列关系"""- blocks = cal_block_index(blocks, sorted_bboxes)-- """将image和table的block还原回group形式参与后续流程"""- blocks = revert_group_blocks(blocks)-- """重排block"""- sorted_blocks = sorted(blocks, key=lambda b: b['index'])-- """block内重排(img和table的block内多个caption或footnote的排序)"""- for block in sorted_blocks:- if block['type'] in [BlockType.IMAGE, BlockType.TABLE]:- block['blocks'] = sorted(block['blocks'], key=lambda b: b['index'])-- return sorted_blocks---def get_line_height(blocks):- page_line_height_list = []- for block in blocks:- if block['type'] in [- BlockType.TEXT, BlockType.TITLE,- BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE- ]:- for line in block['lines']:- bbox = line['bbox']- page_line_height_list.append(int(bbox[3] - bbox[1]))- if len(page_line_height_list) > 0:- return statistics.median(page_line_height_list)- else:- return 10---def sort_lines_by_model(fix_blocks, page_w, page_h, line_height, footnote_blocks):- page_line_list = []-- def add_lines_to_block(b):- line_bboxes = insert_lines_into_block(b['bbox'], line_height, page_w, page_h)- b['lines'] = []- for line_bbox in line_bboxes:- b['lines'].append({'bbox': line_bbox, 'spans': []})- page_line_list.extend(line_bboxes)-- for block in fix_blocks:- if block['type'] in [- BlockType.TEXT, BlockType.TITLE,- BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE- ]:- if len(block['lines']) == 0:- add_lines_to_block(block)- elif block['type'] in [BlockType.TITLE] and len(block['lines']) == 1 and (block['bbox'][3] - block['bbox'][1]) > line_height * 2:- block['real_lines'] = copy.deepcopy(block['lines'])- add_lines_to_block(block)- else:- for line in block['lines']:- bbox = line['bbox']- page_line_list.append(bbox)- elif block['type'] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:- block['real_lines'] = copy.deepcopy(block['lines'])- add_lines_to_block(block)-- for block in footnote_blocks:- footnote_block = {'bbox': block[:4]}- add_lines_to_block(footnote_block)-- if len(page_line_list) > 200: # layoutreader最高支持512line- return None-- # 使用layoutreader排序- x_scale = 1000.0 / page_w- y_scale = 1000.0 / page_h- boxes = []- # logger.info(f"Scale: {x_scale}, {y_scale}, Boxes len: {len(page_line_list)}")- for left, top, right, bottom in page_line_list:- if left < 0:- logger.warning(- f'left < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'- ) # noqa: E501- left = 0- if right > page_w:- logger.warning(- f'right > page_w, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'- ) # noqa: E501- right = page_w- if top < 0:- logger.warning(- f'top < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'- ) # noqa: E501- top = 0- if bottom > page_h:- logger.warning(- f'bottom > page_h, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'- ) # noqa: E501- bottom = page_h-- left = round(left * x_scale)- top = round(top * y_scale)- right = round(right * x_scale)- bottom = round(bottom * y_scale)- assert (- 1000 >= right >= left >= 0 and 1000 >= bottom >= top >= 0- ), f'Invalid box. right: {right}, left: {left}, bottom: {bottom}, top: {top}' # noqa: E126, E121- boxes.append([left, top, right, bottom])- model_manager = ModelSingleton()- model = model_manager.get_model('layoutreader')- with torch.no_grad():- orders = do_predict(boxes, model)- sorted_bboxes = [page_line_list[i] for i in orders]-- return sorted_bboxes---def insert_lines_into_block(block_bbox, line_height, page_w, page_h):- # block_bbox是一个元组(x0, y0, x1, y1),其中(x0, y0)是左下角坐标,(x1, y1)是右上角坐标- x0, y0, x1, y1 = block_bbox-- block_height = y1 - y0- block_weight = x1 - x0-- # 如果block高度小于n行正文,则直接返回block的bbox- if line_height * 2 < block_height:- if (- block_height > page_h * 0.25 and page_w * 0.5 > block_weight > page_w * 0.25- ): # 可能是双列结构,可以切细点- lines = int(block_height / line_height)- else:- # 如果block的宽度超过0.4页面宽度,则将block分成3行(是一种复杂布局,图不能切的太细)- if block_weight > page_w * 0.4:- lines = 3- elif block_weight > page_w * 0.25: # (可能是三列结构,也切细点)- lines = int(block_height / line_height)- else: # 判断长宽比- if block_height / block_weight > 1.2: # 细长的不分- return [[x0, y0, x1, y1]]- else: # 不细长的还是分成两行- lines = 2-- line_height = (y1 - y0) / lines-- # 确定从哪个y位置开始绘制线条- current_y = y0-- # 用于存储线条的位置信息[(x0, y), ...]- lines_positions = []-- for i in range(lines):- lines_positions.append([x0, current_y, x1, current_y + line_height])- current_y += line_height- return lines_positions-- else:- return [[x0, y0, x1, y1]]---def model_init(model_name: str):- from transformers import LayoutLMv3ForTokenClassification- device_name = get_device()- device = torch.device(device_name)- bf_16_support = False- if device_name.startswith("cuda"):- if torch.cuda.get_device_properties(device).major >= 8:- bf_16_support = True- elif device_name.startswith("mps"):- bf_16_support = True- elif device_name.startswith("gcu"):- if hasattr(torch, 'gcu') and torch.gcu.is_available():- if torch.gcu.is_bf16_supported():- bf_16_support = True- elif device_name.startswith("musa"):- if hasattr(torch, 'musa') and torch.musa.is_available():- if torch.musa.is_bf16_supported():- bf_16_support = True- elif device_name.startswith("npu"):- if hasattr(torch, 'npu') and torch.npu.is_available():- if torch.npu.is_bf16_supported():- bf_16_support = True- elif device_name.startswith("mlu"):- if hasattr(torch, 'mlu') and torch.mlu.is_available():- if torch.mlu.is_bf16_supported():- bf_16_support = True- elif device_name.startswith("sdaa"):- if hasattr(torch, 'sdaa') and torch.sdaa.is_available():- if torch.sdaa.is_bf16_supported():- bf_16_support = True-- if model_name == 'layoutreader':- # 检测modelscope的缓存目录是否存在- layoutreader_model_dir = os.path.join(auto_download_and_get_model_root_path(ModelPath.layout_reader), ModelPath.layout_reader)- if os.path.exists(layoutreader_model_dir):- model = LayoutLMv3ForTokenClassification.from_pretrained(- layoutreader_model_dir- )- else:- logger.warning(- 'local layoutreader model not exists, use online model from huggingface'- )- model = LayoutLMv3ForTokenClassification.from_pretrained(- 'hantian/layoutreader'- )- if bf_16_support:- model.to(device).eval().bfloat16()- else:- model.to(device).eval()- else:- logger.error('model name not allow')- exit(1)- return model---class ModelSingleton:- _instance = None- _models = {}-- def __new__(cls, *args, **kwargs):- if cls._instance is None:- cls._instance = super().__new__(cls)- return cls._instance-- def get_model(self, model_name: str):- if model_name not in self._models:- self._models[model_name] = model_init(model_name=model_name)- return self._models[model_name]---def do_predict(boxes: List[List[int]], model) -> List[int]:- from mineru.model.reading_order.layout_reader import (- boxes2inputs, parse_logits, prepare_inputs)-- with warnings.catch_warnings():- warnings.filterwarnings("ignore", category=FutureWarning, module="transformers")-- inputs = boxes2inputs(boxes)- inputs = prepare_inputs(inputs, model)- logits = model(**inputs).logits.cpu().squeeze(0)- return parse_logits(logits, len(boxes))---def cal_block_index(fix_blocks, sorted_bboxes):-- if sorted_bboxes is not None:- # 使用layoutreader排序- for block in fix_blocks:- line_index_list = []- if len(block['lines']) == 0:- block['index'] = sorted_bboxes.index(block['bbox'])- else:- for line in block['lines']:- line['index'] = sorted_bboxes.index(line['bbox'])- line_index_list.append(line['index'])- median_value = statistics.median(line_index_list)- block['index'] = median_value-- # 删除图表body block中的虚拟line信息, 并用real_lines信息回填- if block['type'] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.TITLE, BlockType.INTERLINE_EQUATION]:- if 'real_lines' in block:- block['virtual_lines'] = copy.deepcopy(block['lines'])- block['lines'] = copy.deepcopy(block['real_lines'])- del block['real_lines']- else:- # 使用xycut排序- block_bboxes = []- for block in fix_blocks:- # 如果block['bbox']任意值小于0,将其置为0- block['bbox'] = [max(0, x) for x in block['bbox']]- block_bboxes.append(block['bbox'])-- # 删除图表body block中的虚拟line信息, 并用real_lines信息回填- if block['type'] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.TITLE, BlockType.INTERLINE_EQUATION]:- if 'real_lines' in block:- block['virtual_lines'] = copy.deepcopy(block['lines'])- block['lines'] = copy.deepcopy(block['real_lines'])- del block['real_lines']-- import numpy as np- from mineru.model.reading_order.xycut import recursive_xy_cut-- random_boxes = np.array(block_bboxes)- np.random.shuffle(random_boxes)- res = []- recursive_xy_cut(np.asarray(random_boxes).astype(int), np.arange(len(block_bboxes)), res)- assert len(res) == len(block_bboxes)- sorted_boxes = random_boxes[np.array(res)].tolist()-- for i, block in enumerate(fix_blocks):- block['index'] = sorted_boxes.index(block['bbox'])-- # 生成line index- sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])- line_inedx = 1- for block in sorted_blocks:- for line in block['lines']:- line['index'] = line_inedx- line_inedx += 1-- return fix_blocks---def revert_group_blocks(blocks):- image_groups = {}- table_groups = {}- new_blocks = []- for block in blocks:- if block['type'] in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:- group_id = block['group_id']- if group_id not in image_groups:- image_groups[group_id] = []- image_groups[group_id].append(block)- elif block['type'] in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:- group_id = block['group_id']- if group_id not in table_groups:- table_groups[group_id] = []- table_groups[group_id].append(block)- else:- new_blocks.append(block)-- for group_id, blocks in image_groups.items():- new_blocks.append(process_block_list(blocks, BlockType.IMAGE_BODY, BlockType.IMAGE))-- for group_id, blocks in table_groups.items():- new_blocks.append(process_block_list(blocks, BlockType.TABLE_BODY, BlockType.TABLE))-- return new_blocks---def process_block_list(blocks, body_type, block_type):- indices = [block['index'] for block in blocks]- median_index = statistics.median(indices)-- body_bbox = next((block['bbox'] for block in blocks if block.get('type') == body_type), [])-- return {- 'type': block_type,- 'bbox': body_bbox,- 'blocks': blocks,- 'index': median_index,- }\ No newline at end of file