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 image extraction by adding methods for bounding box retrieval and refining image block processing
myhloli2d3521887ede
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.pyindex 2ae270b8..34c33625 100644--- a/mineru/backend/flash/pdf_extractor.py+++ b/mineru/backend/flash/pdf_extractor.py@@ -41,6 +41,8 @@ _FORMULA_NUMBER_SUFFIX_RE = re.compile(r"^(?P<prefix>.*?)(?P<marker>[((﹙][^()()﹙﹚\r\n]+[))﹚])\s*$")_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")+_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.005+_IMAGE_CONTAINER_OVERLAP_THRESHOLD = 0.5@dataclass(slots=True)@@ -142,12 +144,13 @@ class _FormulaAnchor:@dataclass(slots=True)class _PageSource:- """保存单页原生文本分析所需的文本、字符和绘图线。"""+ """保存单页原生文本分析所需的文本、字符、绘图线和点阵图。"""page_size: tuple[float, float]lines: list[_LineItem]chars: list[Char]drawing_lines: list[_AxisLine]+ image_bboxes: list[BBox] = field(default_factory=list)def extract_pages_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> list[str]:@@ -182,6 +185,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]lines=lines,chars=chars,drawing_lines=drawing_lines,+ image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),)model_list.append(_analyze_page_source(source))return model_list@@ -532,9 +536,9 @@ def _get_pdf_drawing_lines(pdf_doc: PDFDocument, page_idx: int) -> list[_AxisLindef _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:- """按表格、图形、公式、正文的优先级聚合单页文本并排序。"""+ """按表格、图形、点阵图、公式、正文的优先级聚合单页内容并排序。"""- if not source.lines:+ if not source.lines and not source.image_bboxes:return []candidates = _detect_table_candidates(source)table_blocks, claimed_line_indices = _materialize_table_blocks(@@ -547,7 +551,12 @@ def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:table_bboxes,claimed_line_indices,)- claimed_line_indices = claimed_line_indices | claimed_graphic_line_indices+ raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(+ source,+ table_blocks + graphic_blocks,+ claimed_line_indices | claimed_graphic_line_indices,+ )+ claimed_line_indices = claimed_line_indices | claimed_graphic_line_indices | claimed_raster_line_indicesremaining_lines = _merge_same_baseline_text_lines([line for line in source.lines if line.source_index not in claimed_line_indices],source.page_size,@@ -569,7 +578,7 @@ def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:source.page_size,source.drawing_lines,)- absolute_blocks = table_blocks + graphic_blocks + formula_blocks + text_blocks+ absolute_blocks = table_blocks + graphic_blocks + raster_image_blocks + formula_blocks + text_blockssorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, source.page_size)return [normalized for block in sorted_blocks if (normalized := _normalize_output_block(block, source.page_size)) is not None@@ -1375,12 +1384,11 @@ def _is_graphic_label_member(return False-def _graphic_members_to_block(- candidate: _GraphicCandidate,+def _image_members_to_content(members: list[_LineItem],page_size: tuple[float, float],-) -> dict[str, Any] | None:- """按视觉行生成图形标签 content,并用绘图核心和标签并集作为 text bbox。"""+) -> str:+ """按视觉行和页内位置生成图片内部文本,保留不同视觉行之间的换行。"""row_groups: dict[tuple[int, int, int], list[_LineItem]] = {}for line in members:@@ -1402,20 +1410,100 @@ def _graphic_members_to_block(if content:rows.append((row_bbox, content))rows.sort(key=lambda item: (item[0][1], item[0][0]))- content = _sanitize_pdf_control_text(+ return _sanitize_pdf_control_text("\n".join(row_content for _row_bbox, row_content in rows),preserve_newlines=True,).strip()+++def _graphic_members_to_block(+ candidate: _GraphicCandidate,+ members: list[_LineItem],+ page_size: tuple[float, float],+) -> dict[str, Any] | None:+ """生成含内部文本的矢量图 image block,并合并绘图核心与标签 bbox。"""++ content = _image_members_to_content(members, page_size)if not content:return Nonereturn {- "type": "text",+ "type": "image","bbox": _bbox_union(candidate.core_bbox, _bbox_union_many([line.bbox for line in members])),"angle": 0,"content": content,}+def _bbox_area(bbox: BBox) -> float:+ """返回合法 bbox 的非负面积。"""++ return max(0.0, bbox[2] - bbox[0]) * max(0.0, bbox[3] - bbox[1])+++def _build_raster_image_blocks(+ source: _PageSource,+ container_blocks: list[dict[str, Any]],+ claimed_line_indices: set[int],+) -> tuple[list[dict[str, Any]], set[int]]:+ """过滤点阵图、避让高优先级容器,并唯一认领图片内部的原生文本。"""++ page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])+ if page_area <= 0:+ return [], set()++ container_bboxes = [+ bbox+ for block in container_blocks+ if (bbox := _coerce_bbox(block.get("bbox"))) is not None+ ]+ candidate_bboxes: list[BBox] = []+ for raw_bbox in source.image_bboxes:+ bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)+ if bbox is None or _bbox_area(bbox) / page_area < _MIN_RASTER_IMAGE_PAGE_AREA_RATIO:+ continue+ if any(+ _bbox_overlap_in_smaller(bbox, container_bbox) >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD+ for container_bbox in container_bboxes+ ):+ continue+ candidate_bboxes.append(bbox)+ if not candidate_bboxes:+ return [], set()++ members_by_candidate: list[list[_LineItem]] = [[] for _ in candidate_bboxes]+ claimed: set[int] = set()+ for line in source.lines:+ if line.source_index in claimed_line_indices:+ continue+ center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))+ matching_indices = [+ candidate_index+ for candidate_index, bbox in enumerate(candidate_bboxes)+ if _point_in_bbox(center, bbox)+ ]+ if not matching_indices:+ continue+ # 重叠点阵图共享内部文本时归属最小容器,避免 content 重复。+ candidate_index = min(+ matching_indices,+ key=lambda index: (_bbox_area(candidate_bboxes[index]), index),+ )+ members_by_candidate[candidate_index].append(line)+ claimed.add(line.source_index)++ blocks = [+ {+ "type": "image",+ "bbox": bbox,+ "angle": 0,+ "content": _image_members_to_content(members, source.page_size),+ }+ for bbox, members in zip(candidate_bboxes, members_by_candidate, strict=True)+ ]+ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))+ return blocks, claimed++def _candidate_projection_line_indices(source: _PageSource,candidate: _TableCandidate,@@ -2993,13 +3081,15 @@ def _normalize_output_block(if not isinstance(content, str):return Nonecontent = _sanitize_pdf_control_text(content, preserve_newlines=True)- if not content.strip():+ block_type = block.get("type")+ normalized_type = block_type if block_type in {"table", "image"} else "text"+ if normalized_type != "image" and not content.strip():return Nonenormalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)return {- "type": "table" if block.get("type") == "table" else "text",+ "type": normalized_type,"bbox": normalized_bbox,- "angle": int(block.get("angle", 0) or 0) % 360,+ "angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,"content": content,}diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.pyindex 05b8d3d2..f819d603 100644--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@ -321,6 +321,16 @@ class PDFDocument:page_rotation = 0return _extract_page_drawing_lines(page, page_bbox, page_rotation)+ def get_page_image_bboxes(self, page_idx: int) -> list[BBox]:+ """提取页面及嵌套 Form 中的点阵图 bbox,并转换为页面左上原点坐标。"""+ with self._open_page(page_idx) as page:+ page_bbox = _normalize_pdf_page_bbox(page.get_bbox())+ try:+ page_rotation = int(page.get_rotation()) % 360+ except Exception:+ page_rotation = 0+ return _extract_page_image_bboxes(page, page_bbox, page_rotation)+# ------------------------------------------------------------------ ## Classification# ------------------------------------------------------------------ #@@ -474,14 +484,15 @@ def _get_raw_object_matrix(raw_obj: Any) -> tuple[float, float, float, float, fl)-def _walk_raw_path_objects(+def _walk_raw_page_objects(container: Any,*,is_form: bool,parent_matrix: tuple[float, float, float, float, float, float],depth: int,+ target_type: int,) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:- """递归遍历页面或 Form 中的 Path,并携带累积到页面坐标的矩阵。"""+ """递归遍历页面或 Form 中的目标对象,并携带累积到页面坐标的矩阵。"""if depth >= DRAWING_FORM_MAX_DEPTH:return@@ -505,20 +516,38 @@ def _walk_raw_path_objects(continuecombined_matrix = _multiply_pdf_matrices(object_matrix, parent_matrix)except Exception:- # 单个损坏页面对象不能中断同页其他绘图线提取。+ # 单个损坏页面对象不能中断同页其他目标对象遍历。continue- if object_type == pdfium_c.FPDF_PAGEOBJ_PATH:+ if object_type == target_type:yield raw_obj, combined_matrix- elif object_type == pdfium_c.FPDF_PAGEOBJ_FORM:- yield from _walk_raw_path_objects(+ if object_type == pdfium_c.FPDF_PAGEOBJ_FORM:+ yield from _walk_raw_page_objects(raw_obj,is_form=True,parent_matrix=combined_matrix,depth=depth + 1,+ target_type=target_type,)+def _walk_raw_path_objects(+ container: Any,+ *,+ is_form: bool,+ parent_matrix: tuple[float, float, float, float, float, float],+ depth: int,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """递归遍历页面或 Form 中的 Path,并携带累积到页面坐标的矩阵。"""+ yield from _walk_raw_page_objects(+ container,+ is_form=is_form,+ parent_matrix=parent_matrix,+ depth=depth,+ target_type=pdfium_c.FPDF_PAGEOBJ_PATH,+ )++def _iter_raw_path_objects(page: pdfium.PdfPage,) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:@@ -532,6 +561,20 @@ def _iter_raw_path_objects()+def _iter_raw_image_objects(+ page: pdfium.PdfPage,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """从页面根对象开始遍历全部点阵图,包括嵌套 Form 中的图片。"""+ identity = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)+ yield from _walk_raw_page_objects(+ page,+ is_form=False,+ parent_matrix=identity,+ depth=0,+ target_type=pdfium_c.FPDF_PAGEOBJ_IMAGE,+ )++def _get_raw_object_alpha(raw_obj: Any, color_getter: Any) -> int:"""读取对象颜色 alpha;旧 PDFium 或读取失败时按不透明处理。"""red = ctypes.c_uint()@@ -903,6 +946,52 @@ def _merge_collinear_drawing_lines()+def _image_bbox_from_matrix(+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+) -> BBox | None:+ """把点阵图单位矩形经对象/Form 矩阵转换并裁剪为页面左上坐标 bbox。"""+ page_points = [+ _transform_drawing_point(+ _apply_pdf_matrix(point, matrix),+ page_bbox,+ page_rotation,+ )+ for point in ((0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0))+ ]+ coordinates = [coordinate for point in page_points for coordinate in point]+ if not all(math.isfinite(value) for value in coordinates):+ return None++ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ left = max(0.0, min(point[0] for point in page_points))+ top = max(0.0, min(point[1] for point in page_points))+ right = min(page_width, max(point[0] for point in page_points))+ bottom = min(page_height, max(point[1] for point in page_points))+ if right <= left or bottom <= top:+ return None+ return left, top, right, bottom+++def _extract_page_image_bboxes(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[BBox]:+ """在调用方持有 PDFium 锁时提取全部有效点阵图 bbox,并隔离单对象异常。"""+ image_bboxes: list[BBox] = []+ for _raw_obj, matrix in _iter_raw_image_objects(page):+ try:+ image_bbox = _image_bbox_from_matrix(matrix, page_bbox, page_rotation)+ except Exception:+ # 单个损坏 Image 对象不能中断同页其他点阵图提取。+ continue+ if image_bbox is not None:+ image_bboxes.append(image_bbox)+ return sorted(image_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))++def _extract_page_drawing_lines(page: pdfium.PdfPage,page_bbox: BBox,diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.pyindex ea17b460..88c933cc 100644--- a/tests/unittest/test_pdf_document.py+++ b/tests/unittest/test_pdf_document.py@@ -7,6 +7,7 @@ import pytestfrom pypdf import PdfReader, PdfWriterfrom pdftext.schema import Bboxfrom PIL import Image+from reportlab.lib.utils import ImageReaderfrom reportlab.pdfgen.canvas import Canvasfrom mineru.utils import pdf_document@@ -64,6 +65,41 @@ def _build_rotated_cropped_drawing_pdf() -> bytes:return output.getvalue()+def _build_rotated_cropped_image_pdf() -> bytes:+ """构造普通、嵌套 Form、部分页外和完全页外点阵图,并应用 CropBox 与旋转。"""+ image = Image.new("RGB", (3, 4), "red")+ image_buffer = BytesIO()+ image.save(image_buffer, format="PNG")+ image_buffer.seek(0)+ image_reader = ImageReader(image_buffer)++ source = BytesIO()+ canvas = Canvas(source, pagesize=(100, 200))+ canvas.drawImage(image_reader, 10, 20, width=30, height=40)+ canvas.drawImage(image_reader, -10, 170, width=30, height=40)+ canvas.drawImage(image_reader, -30, -30, width=5, height=5)+ canvas.beginForm("NestedImage", 0, 0, 20, 20)+ canvas.drawImage(image_reader, 1, 2, width=3, height=4)+ canvas.endForm()+ canvas.saveState()+ canvas.translate(50, 80)+ canvas.scale(2, 3)+ canvas.doForm("NestedImage")+ canvas.restoreState()+ canvas.save()++ reader = PdfReader(BytesIO(source.getvalue()))+ page = reader.pages[0]+ page.rotate(90)+ page.cropbox.lower_left = (5, 10)+ page.cropbox.upper_right = (95, 190)+ writer = PdfWriter()+ writer.add_page(page)+ output = BytesIO()+ writer.write(output)+ return output.getvalue()++class _TrackingLock:def __init__(self) -> None:self.depth = 0@@ -152,10 +188,20 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pevents.append(f"drawing_lines:{lock.depth}:{page_bbox}:{page_rotation}")return []+ def fake_extract_page_image_bboxes(+ page: _FakePage,+ page_bbox: tuple[float, float, float, float],+ page_rotation: int,+ ) -> list[tuple[float, float, float, float]]:+ """记录点阵图遍历时仍由 PDFDocument 持有 PDFium 锁。"""+ events.append(f"image_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")+ return []+monkeypatch.setattr(pdf_document.pdfium, "PdfDocument", _FakeDoc)monkeypatch.setattr(pdf_document, "get_chars", fake_get_chars, raising=False)monkeypatch.setattr(pdf_document, "pdftext_get_chars", fake_get_chars, raising=False)monkeypatch.setattr(pdf_document, "_extract_page_drawing_lines", fake_extract_page_drawing_lines)+ monkeypatch.setattr(pdf_document, "_extract_page_image_bboxes", fake_extract_page_image_bboxes)doc = pdf_document.PDFDocument(b"%PDF")@@ -165,6 +211,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert image.scale == 3assert doc.get_page_chars(0)[0]["char"] == "A"assert doc.get_page_drawing_lines(0) == []+ assert doc.get_page_image_bboxes(0) == []assert any(event.startswith("doc.open:") and not event.startswith("doc.open:0:") for event in events)assert any(event.startswith("doc.__getitem__:") and not event.startswith("doc.__getitem__:0:") for event in events)@@ -177,6 +224,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert "get_chars:1:[0.0, 10.0, 20.0, 0.0]:0" in eventsassert "textpage.close:1" in eventsassert "drawing_lines:1:(0.0, 0.0, 20.0, 10.0):0" in events+ assert "image_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in eventsdef test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:@@ -231,6 +279,22 @@ def test_get_page_drawing_lines_applies_crop_box_and_page_rotation() -> None:assert line.width == pytest.approx(2.0)+def test_get_page_image_bboxes_applies_forms_crop_box_rotation_and_clipping() -> None:+ """验证点阵图接口递归 Form,并按 CropBox、页面旋转裁剪为左上坐标。"""+ with pdf_document.PDFDocument(_build_rotated_cropped_image_pdf()) as doc:+ page_size = doc.page_size(0)+ image_bboxes = doc.get_page_image_bboxes(0)++ assert page_size == pytest.approx((180.0, 90.0))+ assert image_bboxes == pytest.approx(+ [+ (160.0, 0.0, 180.0, 15.0),+ (10.0, 5.0, 50.0, 35.0),+ (76.0, 47.0, 88.0, 53.0),+ ]+ )++def test_get_page_drawing_lines_skips_one_bad_path(monkeypatch: pytest.MonkeyPatch) -> None:"""验证单个 Path 解析异常不会丢失同页其他有效绘图线。"""original_extract = pdf_document._extract_path_drawing_lines