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: add maximum UTF-8 byte length for task stems and remove unused span processing functions
myhloli708ff455d475
diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex 48b546b7..64b7c5ac 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -34,6 +34,9 @@ xlsx_suffixes = ["xlsx"]office_suffixes = docx_suffixes + pptx_suffixes + xlsx_suffixesos.environ["TOKENIZERS_PARALLELISM"] = "false"+# Maximum UTF-8 byte length allowed for task stems used in filenames.+# 200 bytes is chosen to stay well below common filesystem limits (e.g. 255 bytes)+# and to prevent generating excessively long or incompatible filenames.MAX_TASK_STEM_BYTES = 200diff --git a/mineru/utils/block_pre_proc.py b/mineru/utils/block_pre_proc.pydeleted file mode 100644index 881979ec..00000000--- a/mineru/utils/block_pre_proc.py+++ /dev/null@@ -1,251 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from mineru.utils.boxbase import (- calculate_iou,- calculate_overlap_area_in_bbox1_area_ratio,- calculate_vertical_projection_overlap_ratio,- get_minbox_if_overlap_by_ratio-)-from mineru.utils.enum_class import BlockType---def process_groups(groups, body_key, caption_key, footnote_key):- body_blocks = []- caption_blocks = []- footnote_blocks = []- maybe_text_image_blocks = []- for i, group in enumerate(groups):- if body_key == 'image_body' and len(group[caption_key]) == 0 and len(group[footnote_key]) == 0:- # 如果没有caption和footnote,则不需要将group_id添加到image_body中- group[body_key]['group_id'] = i- maybe_text_image_blocks.append(group[body_key])- continue- else:- group[body_key]['group_id'] = i- body_blocks.append(group[body_key])- for caption_block in group[caption_key]:- caption_block['group_id'] = i- caption_blocks.append(caption_block)- for footnote_block in group[footnote_key]:- footnote_block['group_id'] = i- footnote_blocks.append(footnote_block)- return body_blocks, caption_blocks, footnote_blocks, maybe_text_image_blocks---def prepare_block_bboxes(- img_body_blocks,- img_caption_blocks,- img_footnote_blocks,- table_body_blocks,- table_caption_blocks,- table_footnote_blocks,- discarded_blocks,- text_blocks,- title_blocks,- interline_equation_blocks,- page_w,- page_h,-):- all_bboxes = []-- add_bboxes(img_body_blocks, BlockType.IMAGE_BODY, all_bboxes)- add_bboxes(img_caption_blocks, BlockType.IMAGE_CAPTION, all_bboxes)- add_bboxes(img_footnote_blocks, BlockType.IMAGE_CAPTION, all_bboxes)- add_bboxes(table_body_blocks, BlockType.TABLE_BODY, all_bboxes)- add_bboxes(table_caption_blocks, BlockType.TABLE_CAPTION, all_bboxes)- add_bboxes(table_footnote_blocks, BlockType.TABLE_FOOTNOTE, all_bboxes)- add_bboxes(text_blocks, BlockType.TEXT, all_bboxes)- add_bboxes(title_blocks, BlockType.TITLE, all_bboxes)- add_bboxes(interline_equation_blocks, BlockType.INTERLINE_EQUATION, all_bboxes)-- """block嵌套问题解决"""- """文本框与标题框重叠,优先信任文本框"""- all_bboxes = fix_text_overlap_title_blocks(all_bboxes)- """任何框体与舍弃框重叠,优先信任舍弃框"""- all_bboxes = remove_need_drop_blocks(all_bboxes, discarded_blocks)-- # interline_equation 与title或text框冲突的情况,分两种情况处理- """interline_equation框与文本类型框iou比较接近1的时候,信任行间公式框"""- all_bboxes = fix_interline_equation_overlap_text_blocks_with_hi_iou(all_bboxes)- """interline_equation框被包含在文本类型框内,且interline_equation比文本区块小很多时信任文本框,这时需要舍弃公式框"""- # 通过后续大框套小框逻辑删除-- """discarded_blocks"""- all_discarded_blocks = []- add_bboxes(discarded_blocks, BlockType.DISCARDED, all_discarded_blocks)-- """footnote识别:宽度超过1/3页面宽度的,高度超过10的,处于页面下半30%区域的"""- footnote_blocks = []- for discarded in discarded_blocks:- x0, y0, x1, y1 = discarded['bbox']- if (x1 - x0) > (page_w / 3) and (y1 - y0) > 10 and y0 > (page_h * 0.7):- footnote_blocks.append([x0, y0, x1, y1])-- """移除在footnote下面的任何框"""- need_remove_blocks = find_blocks_under_footnote(all_bboxes, footnote_blocks)- if len(need_remove_blocks) > 0:- for block in need_remove_blocks:- all_bboxes.remove(block)- all_discarded_blocks.append(block)-- """经过以上处理后,还存在大框套小框的情况,则删除小框"""- all_bboxes = remove_overlaps_min_blocks(all_bboxes)- all_discarded_blocks = remove_overlaps_min_blocks(all_discarded_blocks)-- """粗排序后返回"""- all_bboxes.sort(key=lambda x: x[0]+x[1])- return all_bboxes, all_discarded_blocks, footnote_blocks---def add_bboxes(blocks, block_type, bboxes):- for block in blocks:- x0, y0, x1, y1 = block['bbox']- if block_type in [- BlockType.IMAGE_BODY,- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_BODY,- BlockType.TABLE_CAPTION,- BlockType.TABLE_FOOTNOTE,- ]:- bboxes.append([x0, y0, x1, y1, None, None, None, block_type, None, None, None, None, block['score'], block['group_id']])- else:- bboxes.append([x0, y0, x1, y1, None, None, None, block_type, None, None, None, None, block['score']])---def fix_text_overlap_title_blocks(all_bboxes):- # 先提取所有text和title block- text_blocks = []- for block in all_bboxes:- if block[7] == BlockType.TEXT:- text_blocks.append(block)- title_blocks = []- for block in all_bboxes:- if block[7] == BlockType.TITLE:- title_blocks.append(block)-- need_remove = []-- for text_block in text_blocks:- for title_block in title_blocks:- text_block_bbox = text_block[:4]- title_block_bbox = title_block[:4]- if calculate_iou(text_block_bbox, title_block_bbox) > 0.8:- if title_block not in need_remove:- need_remove.append(title_block)-- if len(need_remove) > 0:- for block in need_remove:- all_bboxes.remove(block)-- return all_bboxes---def remove_need_drop_blocks(all_bboxes, discarded_blocks):- need_remove = []- for block in all_bboxes:- for discarded_block in discarded_blocks:- block_bbox = block[:4]- if (- calculate_overlap_area_in_bbox1_area_ratio(- block_bbox, discarded_block['bbox']- )- > 0.6- ):- if block not in need_remove:- need_remove.append(block)- break-- if len(need_remove) > 0:- for block in need_remove:- all_bboxes.remove(block)- return all_bboxes---def fix_interline_equation_overlap_text_blocks_with_hi_iou(all_bboxes):- # 先提取所有text和interline block- text_blocks = []- for block in all_bboxes:- if block[7] == BlockType.TEXT:- text_blocks.append(block)- interline_equation_blocks = []- for block in all_bboxes:- if block[7] == BlockType.INTERLINE_EQUATION:- interline_equation_blocks.append(block)-- need_remove = []-- for interline_equation_block in interline_equation_blocks:- for text_block in text_blocks:- interline_equation_block_bbox = interline_equation_block[:4]- text_block_bbox = text_block[:4]- if calculate_iou(interline_equation_block_bbox, text_block_bbox) > 0.8:- if text_block not in need_remove:- need_remove.append(text_block)-- if len(need_remove) > 0:- for block in need_remove:- all_bboxes.remove(block)-- return all_bboxes---def find_blocks_under_footnote(all_bboxes, footnote_blocks):- need_remove_blocks = []- for block in all_bboxes:- block_x0, block_y0, block_x1, block_y1 = block[:4]- for footnote_bbox in footnote_blocks:- footnote_x0, footnote_y0, footnote_x1, footnote_y1 = footnote_bbox- # 如果footnote的纵向投影覆盖了block的纵向投影的80%且block的y0大于等于footnote的y1- if (- block_y0 >= footnote_y1- and calculate_vertical_projection_overlap_ratio(- (block_x0, block_y0, block_x1, block_y1), footnote_bbox- )- >= 0.8- ):- if block not in need_remove_blocks:- need_remove_blocks.append(block)- break- return need_remove_blocks---def remove_overlaps_min_blocks(all_bboxes):- # 重叠block,小的不能直接删除,需要和大的那个合并成一个更大的。- # 删除重叠blocks中较小的那些- need_remove = []- for i in range(len(all_bboxes)):- for j in range(i + 1, len(all_bboxes)):- block1 = all_bboxes[i]- block2 = all_bboxes[j]- block1_bbox = block1[:4]- block2_bbox = block2[:4]- overlap_box = get_minbox_if_overlap_by_ratio(- block1_bbox, block2_bbox, 0.8- )- if overlap_box is not None:- # 判断哪个区块的面积更小,移除较小的区块- area1 = (block1[2] - block1[0]) * (block1[3] - block1[1])- area2 = (block2[2] - block2[0]) * (block2[3] - block2[1])-- if area1 <= area2:- block_to_remove = block1- large_block = block2- else:- block_to_remove = block2- large_block = block1-- if block_to_remove not in need_remove:- x1, y1, x2, y2 = large_block[:4]- sx1, sy1, sx2, sy2 = block_to_remove[:4]- x1 = min(x1, sx1)- y1 = min(y1, sy1)- x2 = max(x2, sx2)- y2 = max(y2, sy2)- large_block[:4] = [x1, y1, x2, y2]- need_remove.append(block_to_remove)-- for block in need_remove:- if block in all_bboxes:- all_bboxes.remove(block)-- return all_bboxes\ No newline at end of filediff --git a/mineru/utils/format_utils.py b/mineru/utils/format_utils.pydeleted file mode 100644index 7167e9c4..00000000--- a/mineru/utils/format_utils.py+++ /dev/null@@ -1,342 +0,0 @@--import re-import itertools-import html-from typing import Any, Dict, List-from pydantic import (- BaseModel,- computed_field,- model_validator,-)--class TableCell(BaseModel):- """TableCell."""- row_span: int = 1- col_span: int = 1- start_row_offset_idx: int- end_row_offset_idx: int- start_col_offset_idx: int- end_col_offset_idx: int- text: str- column_header: bool = False- row_header: bool = False- row_section: bool = False-- @model_validator(mode="before")- @classmethod- def from_dict_format(cls, data: Any) -> Any:- """from_dict_format."""- if isinstance(data, Dict):- # Check if this is a native BoundingBox or a bbox from docling-ibm-models- if (- # "bbox" not in data- # or data["bbox"] is None- # or isinstance(data["bbox"], BoundingBox)- "text"- in data- ):- return data- text = data["bbox"].get("token", "")- if not len(text):- text_cells = data.pop("text_cell_bboxes", None)- if text_cells:- for el in text_cells:- text += el["token"] + " "-- text = text.strip()- data["text"] = text-- return data---class TableData(BaseModel): # TBD- """BaseTableData."""-- table_cells: List[TableCell] = []- num_rows: int = 0- num_cols: int = 0-- @computed_field # type: ignore- @property- def grid(- self,- ) -> List[List[TableCell]]:- """grid."""- # Initialise empty table data grid (only empty cells)- table_data = [- [- TableCell(- text="",- start_row_offset_idx=i,- end_row_offset_idx=i + 1,- start_col_offset_idx=j,- end_col_offset_idx=j + 1,- )- for j in range(self.num_cols)- ]- for i in range(self.num_rows)- ]-- # Overwrite cells in table data for which there is actual cell content.- for cell in self.table_cells:- for i in range(- min(cell.start_row_offset_idx, self.num_rows),- min(cell.end_row_offset_idx, self.num_rows),- ):- for j in range(- min(cell.start_col_offset_idx, self.num_cols),- min(cell.end_col_offset_idx, self.num_cols),- ):- table_data[i][j] = cell-- return table_data---"""-OTSL-"""-OTSL_NL = "<nl>"-OTSL_FCEL = "<fcel>"-OTSL_ECEL = "<ecel>"-OTSL_LCEL = "<lcel>"-OTSL_UCEL = "<ucel>"-OTSL_XCEL = "<xcel>"---def otsl_extract_tokens_and_text(s: str):- # Pattern to match anything enclosed by < >- # (including the angle brackets themselves)- # pattern = r"(<[^>]+>)"- pattern = r"(" + r"|".join([OTSL_NL, OTSL_FCEL, OTSL_ECEL, OTSL_LCEL, OTSL_UCEL, OTSL_XCEL]) + r")"- # Find all tokens (e.g. "<otsl>", "<loc_140>", etc.)- tokens = re.findall(pattern, s)- # Remove any tokens that start with "<loc_"- tokens = [token for token in tokens]- # Split the string by those tokens to get the in-between text- text_parts = re.split(pattern, s)- text_parts = [token for token in text_parts]- # Remove any empty or purely whitespace strings from text_parts- text_parts = [part for part in text_parts if part.strip()]-- return tokens, text_parts---def otsl_parse_texts(texts, tokens):- split_word = OTSL_NL- split_row_tokens = [- list(y)- for x, y in itertools.groupby(tokens, lambda z: z == split_word)- if not x- ]- table_cells = []- r_idx = 0- c_idx = 0-- # Check and complete the matrix- if split_row_tokens:- max_cols = max(len(row) for row in split_row_tokens)-- # Insert additional <ecel> to tags- for row_idx, row in enumerate(split_row_tokens):- while len(row) < max_cols:- row.append(OTSL_ECEL)-- # Insert additional <ecel> to texts- new_texts = []- text_idx = 0-- for row_idx, row in enumerate(split_row_tokens):- for col_idx, token in enumerate(row):- new_texts.append(token)- if text_idx < len(texts) and texts[text_idx] == token:- text_idx += 1- if (text_idx < len(texts) and- texts[text_idx] not in [OTSL_NL, OTSL_FCEL, OTSL_ECEL, OTSL_LCEL, OTSL_UCEL, OTSL_XCEL]):- new_texts.append(texts[text_idx])- text_idx += 1-- new_texts.append(OTSL_NL)- if text_idx < len(texts) and texts[text_idx] == OTSL_NL:- text_idx += 1-- texts = new_texts-- def count_right(tokens, c_idx, r_idx, which_tokens):- span = 0- c_idx_iter = c_idx- while tokens[r_idx][c_idx_iter] in which_tokens:- c_idx_iter += 1- span += 1- if c_idx_iter >= len(tokens[r_idx]):- return span- return span-- def count_down(tokens, c_idx, r_idx, which_tokens):- span = 0- r_idx_iter = r_idx- while tokens[r_idx_iter][c_idx] in which_tokens:- r_idx_iter += 1- span += 1- if r_idx_iter >= len(tokens):- return span- return span-- for i, text in enumerate(texts):- cell_text = ""- if text in [- OTSL_FCEL,- OTSL_ECEL,- ]:- row_span = 1- col_span = 1- right_offset = 1- if text != OTSL_ECEL:- cell_text = texts[i + 1]- right_offset = 2-- # Check next element(s) for lcel / ucel / xcel,- # set properly row_span, col_span- next_right_cell = ""- if i + right_offset < len(texts):- next_right_cell = texts[i + right_offset]-- next_bottom_cell = ""- if r_idx + 1 < len(split_row_tokens):- if c_idx < len(split_row_tokens[r_idx + 1]):- next_bottom_cell = split_row_tokens[r_idx + 1][c_idx]-- if next_right_cell in [- OTSL_LCEL,- OTSL_XCEL,- ]:- # we have horisontal spanning cell or 2d spanning cell- col_span += count_right(- split_row_tokens,- c_idx + 1,- r_idx,- [OTSL_LCEL, OTSL_XCEL],- )- if next_bottom_cell in [- OTSL_UCEL,- OTSL_XCEL,- ]:- # we have a vertical spanning cell or 2d spanning cell- row_span += count_down(- split_row_tokens,- c_idx,- r_idx + 1,- [OTSL_UCEL, OTSL_XCEL],- )-- table_cells.append(- TableCell(- text=cell_text.strip(),- row_span=row_span,- col_span=col_span,- start_row_offset_idx=r_idx,- end_row_offset_idx=r_idx + row_span,- start_col_offset_idx=c_idx,- end_col_offset_idx=c_idx + col_span,- )- )- if text in [- OTSL_FCEL,- OTSL_ECEL,- OTSL_LCEL,- OTSL_UCEL,- OTSL_XCEL,- ]:- c_idx += 1- if text == OTSL_NL:- r_idx += 1- c_idx = 0- return table_cells, split_row_tokens---def export_to_html(table_data: TableData):- nrows = table_data.num_rows- ncols = table_data.num_cols-- text = ""-- if len(table_data.table_cells) == 0:- return ""-- body = ""-- grid = table_data.grid- for i in range(nrows):- body += "<tr>"- for j in range(ncols):- cell: TableCell = grid[i][j]-- rowspan, rowstart = (- cell.row_span,- cell.start_row_offset_idx,- )- colspan, colstart = (- cell.col_span,- cell.start_col_offset_idx,- )-- if rowstart != i:- continue- if colstart != j:- continue-- content = html.escape(cell.text.strip())- celltag = "td"- if cell.column_header:- celltag = "th"-- opening_tag = f"{celltag}"- if rowspan > 1:- opening_tag += f' rowspan="{rowspan}"'- if colspan > 1:- opening_tag += f' colspan="{colspan}"'-- body += f"<{opening_tag}>{content}</{celltag}>"- body += "</tr>"-- # dir = get_text_direction(text)- body = f"<table>{body}</table>"-- return body---def convert_otsl_to_html(otsl_content: str):- tokens, mixed_texts = otsl_extract_tokens_and_text(otsl_content)- table_cells, split_row_tokens = otsl_parse_texts(mixed_texts, tokens)-- table_data = TableData(- num_rows=len(split_row_tokens),- num_cols=(- max(len(row) for row in split_row_tokens) if split_row_tokens else 0- ),- table_cells=table_cells,- )-- return export_to_html(table_data)---def block_content_to_html(block_content: str) -> str:- """- Converts block content containing OTSL (Open Table Structure Language) tags into HTML.-- This function processes a block of text, splitting it into lines and converting any lines- containing OTSL table tags (e.g., <fcel>, <ecel>) into HTML tables. Lines without these- tags are left unchanged.-- Parameters:- block_content (str): A string containing block content with potential OTSL tags.-- Returns:- str: The processed block content with OTSL tags converted to HTML tables.- """- lines = block_content.split("\n\n")- new_lines = []- for line in lines:- if "<fcel>" in line or "<ecel>" in line:- line = convert_otsl_to_html(line)- new_lines.append(line)- return "\n\n".join(new_lines)diff --git a/mineru/utils/magic_model_utils.py b/mineru/utils/magic_model_utils.pyindex 6756bcc7..13dfac79 100644--- a/mineru/utils/magic_model_utils.py+++ b/mineru/utils/magic_model_utils.py@@ -28,148 +28,6 @@ def reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:return [bboxes[i] for i in range(N) if keep[i]]-def tie_up_category_by_distance_v3(- get_subjects_func: Callable,- get_objects_func: Callable,- extract_subject_func: Callable = None,- extract_object_func: Callable = None-):- """- 通用的类别关联方法,用于将主体对象与客体对象进行关联-- 参数:- get_subjects_func: 函数,提取主体对象- get_objects_func: 函数,提取客体对象- extract_subject_func: 函数,自定义提取主体属性(默认使用bbox和其他属性)- extract_object_func: 函数,自定义提取客体属性(默认使用bbox和其他属性)-- 返回:- 关联后的对象列表- """- subjects = get_subjects_func()- objects = get_objects_func()-- # 如果没有提供自定义提取函数,使用默认函数- if extract_subject_func is None:- extract_subject_func = lambda x: x- if extract_object_func is None:- extract_object_func = lambda x: x-- ret = []- N, M = len(subjects), len(objects)- subjects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)- objects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)-- OBJ_IDX_OFFSET = 10000- SUB_BIT_KIND, OBJ_BIT_KIND = 0, 1-- all_boxes_with_idx = [(i, SUB_BIT_KIND, sub["bbox"][0], sub["bbox"][1]) for i, sub in enumerate(subjects)] + [- (i + OBJ_IDX_OFFSET, OBJ_BIT_KIND, obj["bbox"][0], obj["bbox"][1]) for i, obj in enumerate(objects)- ]- seen_idx = set()- seen_sub_idx = set()-- while N > len(seen_sub_idx):- candidates = []- for idx, kind, x0, y0 in all_boxes_with_idx:- if idx in seen_idx:- continue- candidates.append((idx, kind, x0, y0))-- if len(candidates) == 0:- break- left_x = min([v[2] for v in candidates])- top_y = min([v[3] for v in candidates])-- candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)-- fst_idx, fst_kind, left_x, top_y = candidates[0]- fst_bbox = subjects[fst_idx]['bbox'] if fst_kind == SUB_BIT_KIND else objects[fst_idx - OBJ_IDX_OFFSET]['bbox']- candidates.sort(- key=lambda x: bbox_distance(fst_bbox, subjects[x[0]]['bbox']) if x[1] == SUB_BIT_KIND else bbox_distance(- fst_bbox, objects[x[0] - OBJ_IDX_OFFSET]['bbox']))- nxt = None-- for i in range(1, len(candidates)):- if candidates[i][1] ^ fst_kind == 1:- nxt = candidates[i]- break- if nxt is None:- break-- if fst_kind == SUB_BIT_KIND:- sub_idx, obj_idx = fst_idx, nxt[0] - OBJ_IDX_OFFSET- else:- sub_idx, obj_idx = nxt[0], fst_idx - OBJ_IDX_OFFSET-- pair_dis = bbox_distance(subjects[sub_idx]["bbox"], objects[obj_idx]["bbox"])- nearest_dis = float("inf")- for i in range(N):- # 取消原先算法中 1对1 匹配的偏置- # if i in seen_idx or i == sub_idx:continue- nearest_dis = min(nearest_dis, bbox_distance(subjects[i]["bbox"], objects[obj_idx]["bbox"]))-- if pair_dis >= 3 * nearest_dis:- seen_idx.add(sub_idx)- continue-- seen_idx.add(sub_idx)- seen_idx.add(obj_idx + OBJ_IDX_OFFSET)- seen_sub_idx.add(sub_idx)-- ret.append(- {- "sub_bbox": extract_subject_func(subjects[sub_idx]),- "obj_bboxes": [extract_object_func(objects[obj_idx])],- "sub_idx": sub_idx,- }- )-- for i in range(len(objects)):- j = i + OBJ_IDX_OFFSET- if j in seen_idx:- continue- seen_idx.add(j)- nearest_dis, nearest_sub_idx = float("inf"), -1- for k in range(len(subjects)):- dis = bbox_distance(objects[i]["bbox"], subjects[k]["bbox"])- if dis < nearest_dis:- nearest_dis = dis- nearest_sub_idx = k-- for k in range(len(subjects)):- if k != nearest_sub_idx:- continue- if k in seen_sub_idx:- for kk in range(len(ret)):- if ret[kk]["sub_idx"] == k:- ret[kk]["obj_bboxes"].append(extract_object_func(objects[i]))- break- else:- ret.append(- {- "sub_bbox": extract_subject_func(subjects[k]),- "obj_bboxes": [extract_object_func(objects[i])],- "sub_idx": k,- }- )- seen_sub_idx.add(k)- seen_idx.add(k)-- for i in range(len(subjects)):- if i in seen_sub_idx:- continue- ret.append(- {- "sub_bbox": extract_subject_func(subjects[i]),- "obj_bboxes": [],- "sub_idx": i,- }- )-- return ret--def tie_up_category_by_index(get_subjects_func: Callable,get_objects_func: Callable,diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.pyindex 0b0b6508..ecb850a1 100644--- a/mineru/utils/model_utils.py+++ b/mineru/utils/model_utils.py@@ -46,10 +46,6 @@ def _get_int_bbox(item):return math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)-def _set_bbox(item, bbox):- item["bbox"] = [float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3])]--def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):crop_xmin, crop_ymin, crop_xmax, crop_ymax = _get_int_bbox(input_res)diff --git a/mineru/utils/run_async.py b/mineru/utils/run_async.pydeleted file mode 100644index 7282ec19..00000000--- a/mineru/utils/run_async.py+++ /dev/null@@ -1,52 +0,0 @@-import asyncio-import threading-from queue import Queue-from typing import Any, AsyncIterable, Coroutine, Iterable, TypeVar--T = TypeVar("T")---def run_async(coroutine: Coroutine[Any, Any, T]) -> T:- if not asyncio.iscoroutine(coroutine):- raise ValueError("a coroutine was expected, got {!r}".format(coroutine))-- try:- loop = asyncio.get_running_loop()- except RuntimeError:- loop = None-- if loop is not None:- return loop.run_until_complete(coroutine)- else:- return asyncio.run(coroutine)---def iter_async(iterable: AsyncIterable[T]) -> Iterable[T]:- if not isinstance(iterable, AsyncIterable):- raise ValueError("an async iterable was expected, got {!r}".format(iterable))-- queue = Queue()-- async def async_helper():- try:- async for chunk in iterable:- queue.put(chunk)- queue.put(None)- except Exception as e:- queue.put(e)-- def helper():- run_async(async_helper())-- thread = threading.Thread(target=helper, daemon=True)- thread.start()-- while True:- chunk = queue.get()- if chunk is None:- break- if isinstance(chunk, Exception):- raise chunk- yield chunk-- thread.join()diff --git a/mineru/utils/span_pre_proc.py b/mineru/utils/span_pre_proc.pyindex cb8defbc..4377110d 100644--- a/mineru/utils/span_pre_proc.py+++ b/mineru/utils/span_pre_proc.py@@ -8,105 +8,12 @@ import cv2import numpy as npfrom loguru import logger-from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio, calculate_iou, \- get_minbox_if_overlap_by_ratio+from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom mineru.utils.enum_class import BlockType, ContentTypefrom mineru.utils.pdf_image_tools import get_crop_imgfrom mineru.utils.pdf_text_tool import get_page-def remove_outside_spans(spans, all_bboxes, all_discarded_blocks):- def get_block_bboxes(blocks, block_type_list):- return [block[0:4] for block in blocks if block[7] in block_type_list]-- image_bboxes = get_block_bboxes(all_bboxes, [BlockType.IMAGE_BODY])- table_bboxes = get_block_bboxes(all_bboxes, [BlockType.TABLE_BODY])- other_block_type = []- for block_type in BlockType.__dict__.values():- if not isinstance(block_type, str):- continue- if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY]:- other_block_type.append(block_type)- other_block_bboxes = get_block_bboxes(all_bboxes, other_block_type)- discarded_block_bboxes = get_block_bboxes(all_discarded_blocks, [BlockType.DISCARDED])-- new_spans = []-- for span in spans:- span_bbox = span['bbox']- span_type = span['type']-- if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.4 for block_bbox in- discarded_block_bboxes):- new_spans.append(span)- continue-- if span_type == ContentType.IMAGE:- if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in- image_bboxes):- new_spans.append(span)- elif span_type == ContentType.TABLE:- if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in- table_bboxes):- new_spans.append(span)- else:- if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in- other_block_bboxes):- new_spans.append(span)-- return new_spans---def remove_overlaps_low_confidence_spans(spans):- dropped_spans = []- # 删除重叠spans中置信度低的的那些- for span1 in spans:- for span2 in spans:- if span1 != span2:- # span1 或 span2 任何一个都不应该在 dropped_spans 中- if span1 in dropped_spans or span2 in dropped_spans:- continue- else:- if calculate_iou(span1['bbox'], span2['bbox']) > 0.9:- if span1['score'] < span2['score']:- span_need_remove = span1- else:- span_need_remove = span2- if (- span_need_remove is not None- and span_need_remove not in dropped_spans- ):- dropped_spans.append(span_need_remove)-- if len(dropped_spans) > 0:- for span_need_remove in dropped_spans:- spans.remove(span_need_remove)-- return spans, dropped_spans---def remove_overlaps_min_spans(spans):- dropped_spans = []- # 删除重叠spans中较小的那些- for span1 in spans:- for span2 in spans:- if span1 != span2:- # span1 或 span2 任何一个都不应该在 dropped_spans 中- if span1 in dropped_spans or span2 in dropped_spans:- continue- else:- overlap_box = get_minbox_if_overlap_by_ratio(span1['bbox'], span2['bbox'], 0.65)- if overlap_box is not None:- span_need_remove = next((span for span in spans if span['bbox'] == overlap_box), None)- if span_need_remove is not None and span_need_remove not in dropped_spans:- dropped_spans.append(span_need_remove)- if len(dropped_spans) > 0:- for span_need_remove in dropped_spans:- spans.remove(span_need_remove)-- return spans, dropped_spans--def __replace_ligatures(text: str):ligatures = {'fi': 'fi', 'fl': 'fl', 'ff': 'ff', 'ffi': 'ffi', 'ffl': 'ffl', 'ſt': 'ft', 'st': 'st'