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: enhance PDF character processing with compatibility for legacy structures and improved span filling
myhlolib0f00633a0ae
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.pyindex 3bd1f034..96361294 100644--- a/mineru/backend/utils/span_pre_proc.py+++ b/mineru/backend/utils/span_pre_proc.py@@ -66,7 +66,7 @@ def txt_spans_extract(return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)page_chars = pdf_page.get_chars()- page_all_chars = [char for char in page_chars if _is_supported_rotation(char["rotation"])]+ page_all_chars = _get_chars_for_span_fill(page_chars)# 计算所有span的高度的中位数span_height_list = []@@ -132,6 +132,84 @@ def _is_supported_rotation(rotation: float) -> bool:return any(abs(rotation_degrees - angle) < 0.1 for angle in [0, 90, 180, 270])+def _get_char_fill_key(char: Char) -> tuple[str, Any]:+ """生成字符回填判定 key,优先使用 pdftext 提供的页内 char_idx。"""+ char_idx = char.get("char_idx")+ if char_idx is not None:+ return ("char_idx", char_idx)+ return ("object_id", id(char))+++def _iter_line_chars(line: dict[str, Any]) -> list[Char]:+ """按 pdftext line/span 结构展开字符,兼容缺少 chars 字段的异常 span。"""+ return [+ char+ for span in line.get("spans", [])+ for char in span.get("chars", [])+ ]+++def _is_visible_standard_rotation_char(char: Char) -> bool:+ """判断字符是否是可见的标准方向正文字符,避免换行控制符误放行水印。"""+ text = str(char.get("char", ""))+ if not text or text.isspace() or text in {"\r", "\n"}:+ return False++ bbox = char.get("bbox")+ if bbox is None:+ return False++ x0, y0, x1, y1 = [float(v) for v in bbox]+ return (+ x1 > x0+ and y1 > y0+ and _is_supported_rotation(float(char.get("rotation", 0)))+ )+++def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) -> list[Char]:+ """选择允许参与 span 回填的字符,保留正文内仿斜体并过滤整行斜向水印。"""+ if isinstance(page_chars, dict):+ all_chars = page_chars["chars"]+ else:+ all_chars = page_chars++ fill_char_keys = {+ _get_char_fill_key(char)+ for char in all_chars+ if _is_supported_rotation(float(char.get("rotation", 0)))+ }++ rotated_chars = [+ char+ for char in all_chars+ if not _is_supported_rotation(float(char.get("rotation", 0)))+ ]+ if not rotated_chars:+ return [+ char for char in all_chars+ if _get_char_fill_key(char) in fill_char_keys+ ]++ for line in get_lines_from_chars(all_chars):+ if not _is_supported_rotation(float(line.get("rotation", 0))):+ continue++ line_chars = _iter_line_chars(line)+ if not any(_is_visible_standard_rotation_char(char) for char in line_chars):+ continue++ # 标准方向正文行内的局部旋转字符通常是仿斜体强调,需要允许回填。+ for char in line_chars:+ if not _is_supported_rotation(float(char.get("rotation", 0))):+ fill_char_keys.add(_get_char_fill_key(char))++ return [+ char for char in all_chars+ if _get_char_fill_key(char) in fill_char_keys+ ]++def _prepare_post_ocr_spans(need_ocr_spans: list[Span],spans: list[Span],diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex 1c4b984a..be745bc9 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -58,6 +58,8 @@ PP_DOCLAYOUT_V2_LABELS = ["vision_footnote", # 24 image/chart/table的footnote]+PP_DOCLAYOUT_V2_LABEL_TO_ID = {label: index for index, label in enumerate(PP_DOCLAYOUT_V2_LABELS)}+# Per-class confidence threshold used before reading-order decoding.DEFAULT_CLASS_THRESHOLDS = [0.5, # 0 abstract@@ -797,6 +799,16 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):self.reading_order = PPDocLayoutV2ReadingOrder(config.reading_order_config)self.num_queries = config.num_queriesself.config = config+ self.register_buffer(+ "_class_thresholds_tensor",+ torch.tensor(config.class_thresholds, dtype=torch.float32),+ persistent=False,+ )+ self.register_buffer(+ "_class_order_tensor",+ torch.tensor(config.class_order, dtype=torch.long),+ persistent=False,+ )self.post_init()def forward(@@ -837,8 +849,7 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):max_logits, class_ids = logits.max(dim=-1)max_probs = max_logits.sigmoid()- class_thresholds = torch.tensor(self.config.class_thresholds, dtype=torch.float32, device=logits.device)- thresholds = class_thresholds[class_ids]+ thresholds = self._class_thresholds_tensor[class_ids]mask = max_probs >= thresholdsindices = torch.argsort(mask.to(torch.int8), dim=1, descending=True)@@ -850,8 +861,7 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):pad_boxes = torch.where(sorted_mask[..., None], sorted_boxes, torch.zeros_like(sorted_boxes))pad_class_ids = torch.where(sorted_mask, sorted_class_ids, torch.zeros_like(sorted_class_ids))- class_order = torch.tensor(self.config.class_order, dtype=torch.long, device=logits.device)- pad_class_ids = class_order[pad_class_ids]+ pad_class_ids = self._class_order_tensor[pad_class_ids]order_logits = self.reading_order(boxes=pad_boxes,@@ -886,6 +896,17 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):class PPDocLayoutV2LayoutModel:+ HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS = {"aside_text", "footnote", "number"}+ PAGE_REGION_LABELS = {+ "header",+ "header_image",+ "footer",+ "footer_image",+ "footnote",+ "number",+ "aside_text",+ }+def __init__(self,weight: str,@@ -1060,6 +1081,85 @@ class PPDocLayoutV2LayoutModel:return 0.0return cls._calculate_intersection_area(box1, box2) / box1_area+ @staticmethod+ def _calculate_x_overlap_ratio(box1: Sequence[float], box2: Sequence[float]) -> float:+ """计算两个 bbox 在横向上的重叠比例,用于判断是否属于同一栏。"""+ box1_xmin, _, box1_xmax, _ = [float(v) for v in box1]+ box2_xmin, _, box2_xmax, _ = [float(v) for v in box2]+ box1_width = max(0.0, box1_xmax - box1_xmin)+ box2_width = max(0.0, box2_xmax - box2_xmin)+ ref_width = min(box1_width, box2_width)+ if ref_width <= 0.0:+ return 0.0+ overlap_width = max(0.0, min(box1_xmax, box2_xmax) - max(box1_xmin, box2_xmin))+ return overlap_width / ref_width++ @staticmethod+ def _calculate_x_cover_ratio(anchor_box: Sequence[float], candidate_box: Sequence[float]) -> float:+ """计算 anchor 在横向上覆盖 candidate 的比例。"""+ anchor_xmin, _, anchor_xmax, _ = [float(v) for v in anchor_box]+ candidate_xmin, _, candidate_xmax, _ = [float(v) for v in candidate_box]+ candidate_width = max(0.0, candidate_xmax - candidate_xmin)+ if candidate_width <= 0.0:+ return 0.0+ overlap_width = max(+ 0.0,+ min(anchor_xmax, candidate_xmax) - max(anchor_xmin, candidate_xmin),+ )+ return overlap_width / candidate_width++ @classmethod+ def _is_footer_x_scope(+ cls,+ anchor_box: Dict,+ candidate_box: Dict,+ image_size: Optional[Tuple[int, int]],+ full_width_threshold: float = 0.7,+ x_overlap_threshold: float = 0.3,+ ) -> bool:+ """判断候选块是否在页脚文本锚点的横向作用范围内。"""+ anchor_bbox = anchor_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not anchor_bbox or not candidate_bbox:+ return False++ if image_size is not None and len(image_size) >= 2:+ page_width = float(image_size[1])+ anchor_width = max(0.0, float(anchor_bbox[2]) - float(anchor_bbox[0]))+ if page_width > 0.0 and anchor_width / page_width >= full_width_threshold:+ return True++ return cls._calculate_x_overlap_ratio(anchor_bbox, candidate_bbox) >= x_overlap_threshold++ @classmethod+ def _is_covered_by_footnote(+ cls,+ footnote_box: Dict,+ candidate_box: Dict,+ x_cover_threshold: float = 0.7,+ ) -> bool:+ """判断候选块是否位于 footnote 区域内或其下方,并被其横向覆盖。"""+ footnote_bbox = footnote_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not footnote_bbox or not candidate_bbox:+ return False+ if candidate_bbox[1] < footnote_bbox[1]:+ return False+ return cls._calculate_x_cover_ratio(footnote_bbox, candidate_bbox) >= x_cover_threshold++ @classmethod+ def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:+ """判断普通块是否可被页眉/页脚/页码边界规则改标。"""+ label = box.get("label")+ if label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:+ return False+ return label not in anchor_labels++ @classmethod+ def _is_footnote_relabel_candidate(cls, box: Dict) -> bool:+ """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""+ return box.get("label") not in cls.PAGE_REGION_LABELS+@staticmethoddef _is_reference_box(box: Dict) -> bool:return box.get("label") == "reference" or int(box.get("cls_id", -1)) == 18@@ -1083,30 +1183,31 @@ class PPDocLayoutV2LayoutModel:def _is_formula_number_box(box: Dict) -> bool:return box.get("label") == "formula_number" or int(box.get("cls_id", -1)) == 11+ @staticmethod+ def _set_box_label(box: Dict, label: str) -> None:+ """统一同步设置 layout 检测框的标签名和类别编号。"""+ if label not in PP_DOCLAYOUT_V2_LABEL_TO_ID:+ raise ValueError(f"Unsupported PP-DocLayoutV2 label: {label}")+ box["label"] = label+ box["cls_id"] = PP_DOCLAYOUT_V2_LABEL_TO_ID[label]+@staticmethoddef _set_formula_label(box: Dict, label: str) -> None:- if label == "inline_formula":- cls_id = 15- elif label == "display_formula":- cls_id = 5- else:+ if label not in {"inline_formula", "display_formula"}:raise ValueError(f"Unsupported formula label: {label}")- box["label"] = label- box["cls_id"] = cls_id+ PPDocLayoutV2LayoutModel._set_box_label(box, label)@staticmethoddef _set_header_footer_label(box: Dict, label: str) -> None:"""同步设置页眉/页脚相关标签及其类别编号。"""- label_cls_ids = {- "footer": 8,- "footer_image": 9,- "header": 12,- "header_image": 13,- }- if label not in label_cls_ids:+ if label not in {"footer", "footer_image", "header", "header_image"}:raise ValueError(f"Unsupported header/footer label: {label}")- box["label"] = label- box["cls_id"] = label_cls_ids[label]+ PPDocLayoutV2LayoutModel._set_box_label(box, label)++ @staticmethod+ def _set_footnote_label(box: Dict) -> None:+ """同步设置 page footnote 标签及其类别编号。"""+ PPDocLayoutV2LayoutModel._set_box_label(box, "footnote")@classmethoddef _reclassify_header_footer_by_page_half(@@ -1280,7 +1381,6 @@ class PPDocLayoutV2LayoutModel:header_labels = {"header", "header_image"}footer_labels = {"footer", "footer_image"}- exempt_labels = {"aside_text", "footnote", "number"}ordered_boxes = sorted(boxes, key=lambda box: box["index"])ordered_boxes = cls._reclassify_header_footer_by_page_half(ordered_boxes,@@ -1307,22 +1407,31 @@ class PPDocLayoutV2LayoutModel:if header_anchor is not None:header_boundary = header_anchor["bbox"][3]for box in ordered_boxes:- label = box.get("label")- if label in exempt_labels or label in header_labels:+ if not cls._is_header_footer_boundary_candidate(box, header_labels):continueif box["bbox"][3] <= header_boundary:- box["label"] = "header"- box["cls_id"] = 12+ cls._set_box_label(box, "header")++ footnote_anchors = [box for box in ordered_boxes if box.get("label") == "footnote"]+ if footnote_anchors:+ for box in ordered_boxes:+ if not cls._is_footnote_relabel_candidate(box):+ continue+ for footnote_anchor in footnote_anchors:+ if cls._is_covered_by_footnote(footnote_anchor, box):+ cls._set_footnote_label(box)+ breakif footer_anchor is not None:footer_boundary = footer_anchor["bbox"][1]for box in ordered_boxes:- label = box.get("label")- if label in exempt_labels or label in footer_labels:+ if not cls._is_header_footer_boundary_candidate(box, footer_labels):continue- if box["bbox"][1] >= footer_boundary:- box["label"] = "footer"- box["cls_id"] = 8+ if (+ box["bbox"][1] >= footer_boundary+ and cls._is_footer_x_scope(footer_anchor, box, image_size)+ ):+ cls._set_box_label(box, "footer")if image_size is None:return ordered_boxes@@ -1359,20 +1468,24 @@ class PPDocLayoutV2LayoutModel:if top_number_anchor is not None:header_boundary = top_number_anchor["bbox"][1]for box in ordered_boxes:- if id(box) in boundary_anchor_ids or box.get("label") in exempt_labels:+ if (+ id(box) in boundary_anchor_ids+ or not cls._is_header_footer_boundary_candidate(box, set())+ ):continueif box["bbox"][3] <= header_boundary:- box["label"] = "header"- box["cls_id"] = 12+ cls._set_box_label(box, "header")if bottom_number_anchor is not None:footer_boundary = bottom_number_anchor["bbox"][3]for box in ordered_boxes:- if id(box) in boundary_anchor_ids or box.get("label") in exempt_labels:+ if (+ id(box) in boundary_anchor_ids+ or not cls._is_header_footer_boundary_candidate(box, set())+ ):continueif box["bbox"][1] >= footer_boundary:- box["label"] = "footer"- box["cls_id"] = 8+ cls._set_box_label(box, "footer")return ordered_boxesdiff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.pyindex 7232cfc3..c453f484 100644--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@ -5,12 +5,13 @@ import asyncioimport osfrom contextlib import contextmanagerfrom io import BytesIO-from typing import Iterator, Literal, TypeAlias, cast+from typing import Any, Iterator, Literal, TypeAlias, cast+import numpy as npimport pypdfium2 as pdfiumfrom pdftext.pdf.chars import deduplicate_chars, get_charsfrom pdftext.pdf.pages import assign_scripts, get_lines, get_spans-from pdftext.schema import Char, Line+from pdftext.schema import Bbox, Char, Linefrom PIL import Image, ImageOpsfrom ..types import BBox, PageInfo@@ -26,6 +27,11 @@ DEFAULT_RENDER_SCALE: float = DEFAULT_RENDER_DPI / POINTS_PER_INCHDEFAULT_RENDER_MAX_EDGE: int = 3500NEAR_DUPLICATE_CHAR_BBOX_TOLERANCE = 0.5+try:+ from pdftext.pdf.chars import PageChars+except ImportError:+ PageChars = None+# See: pdfium.PdfDocument.METADATA_KEYSPDFMetadataKey: TypeAlias = Literal["Title",@@ -232,7 +238,9 @@ class PDFDocument:chars = get_chars(textpage, page_bbox, page_rotation)finally:_try_close(textpage)- return _deduplicate_near_identical_chars(deduplicate_chars(chars))+ chars = _deduplicate_pdftext_chars(chars)+ chars = _ensure_legacy_chars(chars)+ return _deduplicate_near_identical_chars(chars)def get_page_lines(self, page_idx: int) -> list[Line]:chars = self.get_page_chars(page_idx)@@ -362,6 +370,47 @@ def _deduplicate_near_identical_chars(chars: list[Char]) -> list[Char]:return unique_chars+def _is_pdftext_page_chars(chars: Any) -> bool:+ """判断对象是否为 pdftext 0.7 引入的 PageChars 列式字符容器。"""+ return PageChars is not None and isinstance(chars, PageChars)+++def _deduplicate_pdftext_chars(chars: Any) -> Any:+ """按当前 pdftext 返回类型调用官方去重,兼容测试或旧版本的 list 字符。"""+ if _is_pdftext_page_chars(chars) or PageChars is None:+ return deduplicate_chars(chars)+ return chars+++def _materialize_page_chars(chars: Any) -> list[Char]:+ """将 pdftext 0.7 的 PageChars 物化为 MinerU 既有 char dict 列表。"""+ boxes = chars.boxes.tolist()+ rotations = chars.rotations.tolist()+ font_ids = chars.font_ids.tolist()+ char_indices = chars.char_indices.tolist()++ return [+ cast(+ Char,+ {+ "bbox": Bbox([float(coord) for coord in boxes[index]]),+ "char": chars.text[index],+ "rotation": float(rotations[index]),+ "font": chars.fonts[int(font_ids[index])],+ "char_idx": int(char_indices[index]),+ },+ )+ for index in range(len(chars))+ ]+++def _ensure_legacy_chars(chars: Any) -> list[Char]:+ """统一输出旧版 char dict 列表,隔离 pdftext 0.7 的返回结构变化。"""+ if _is_pdftext_page_chars(chars):+ return _materialize_page_chars(chars)+ return cast(list[Char], chars)++def _char_bbox_values(bbox: object) -> tuple[float, float, float, float] | None:"""将 tuple/list 或 pdftext Bbox 对象统一转换为四元组坐标。"""if bbox is None:@@ -375,12 +424,94 @@ def _char_bbox_values(bbox: object) -> tuple[float, float, float, float] | None:return None+def _get_single_char_text(char: Char) -> str:+ """提取单个 PDF 字符文本,异常空值用替换符保证 PageChars 长度一致。"""+ text = str(char.get("char", ""))+ if len(text) == 1:+ return text+ return text[:1] or "\uFFFD"+++def _get_char_font_id(+ char: Char,+ fonts: list[dict[str, Any]],+ font_cache: dict[tuple[Any, Any, Any, Any], int],+) -> int:+ """为旧版字符 font 生成 PageChars 需要的页内 font id。"""+ font = char.get("font") or {}+ font_key = (+ font.get("name"),+ font.get("flags"),+ font.get("size"),+ font.get("weight"),+ )+ font_id = font_cache.get(font_key)+ if font_id is None:+ font_id = len(fonts)+ font_cache[font_key] = font_id+ fonts.append(+ {+ "name": font.get("name"),+ "flags": font.get("flags"),+ "size": font.get("size"),+ "weight": font.get("weight"),+ }+ )+ return font_id+++def _get_char_index(char: Char, fallback_idx: int) -> int:+ """提取旧版字符索引,缺失或为空时回退到当前列表位置。"""+ char_idx = char.get("char_idx")+ if char_idx is None:+ char_idx = fallback_idx+ return int(char_idx)+++def _legacy_chars_to_page_chars(chars: Any) -> Any:+ """将旧版 char dict 列表打包回 pdftext 0.7 get_spans 所需的 PageChars。"""+ if PageChars is None or _is_pdftext_page_chars(chars):+ return chars++ fonts: list[dict[str, Any]] = []+ font_cache: dict[tuple[Any, Any, Any, Any], int] = {}+ text_parts: list[str] = []+ codes: list[int] = []+ rotations: list[float] = []+ boxes: list[tuple[float, float, float, float]] = []+ font_ids: list[int] = []+ char_indices: list[int] = []++ for fallback_idx, char in enumerate(cast(list[Char], chars)):+ char_text = _get_single_char_text(char)+ bbox_values = _char_bbox_values(char.get("bbox"))+ if bbox_values is None:+ bbox_values = (0.0, 0.0, 0.0, 0.0)+ text_parts.append(char_text)+ codes.append(ord(char_text))+ rotations.append(float(char.get("rotation") or 0.0))+ boxes.append(bbox_values)+ font_ids.append(_get_char_font_id(char, fonts, font_cache))+ char_indices.append(_get_char_index(char, fallback_idx))++ return PageChars(+ "".join(text_parts),+ np.array(codes, dtype=np.uint32),+ np.array(rotations, dtype=np.float64),+ np.array(boxes, dtype=np.float64).reshape((len(boxes), 4)),+ np.array(font_ids, dtype=np.int32),+ fonts,+ np.array(char_indices, dtype=np.int64),+ )++def get_lines_from_chars(chars: list[Char],superscript_height_threshold: float = 0.7,line_distance_threshold: float = 0.1,) -> list[Line]:"""从已提取的字符构建 pdftext lines,避免重复读取 PDFium textpage。"""+ chars = _legacy_chars_to_page_chars(chars)spans = get_spans(chars,superscript_height_threshold=superscript_height_threshold,diff --git a/pyproject.toml b/pyproject.tomlindex effd8682..070c9032 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,7 +42,7 @@ dependencies = ["pypdf>=5.6.0","PyYAML>=6.0.1,<7","reportlab",- "pdftext>=0.6.3",+ "pdftext>=0.6.3,<0.8.0","modelscope>=1.26.0","huggingface-hub>=0.32.4","json-repair>=0.46.2",