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
address latest HTML parser review findings
myhlolib5d0a1dc553e
diff --git a/mineru/model/flash/_shared/markup/projector.py b/mineru/model/flash/_shared/markup/projector.pyindex 06dcfefc..bc092b2e 100644--- a/mineru/model/flash/_shared/markup/projector.py+++ b/mineru/model/flash/_shared/markup/projector.py@@ -139,6 +139,16 @@ def _append_inline_segment(segments.append(segment)+def _append_list_block_content(parts: list[str], rendered: str) -> None:+ """用换行包围列表项内的块级正文,避免相邻段落静默粘连。"""+ if not rendered.strip():+ return+ last_visible = next((part for part in reversed(parts) if part), "")+ if last_visible and not last_visible.endswith("\n"):+ parts.append("\n")+ parts.extend((rendered, "\n"))++def entity_text(element: etree._Element) -> str:"""把 lxml 保留的安全命名实体恢复为可见文本。"""name = getattr(element, "name", "")@@ -569,6 +579,11 @@ class MarkupProjector:annotation_elements=annotation_elements,emit_alt_caption=not mineru_figure and not annotations,)+ annotation_targets = self._figure_annotation_targets(+ element,+ annotation_elements,+ visual_blocks_by_child,+ )annotations_by_visual: dict[int, list[dict[str, object]]] = {}unbound_annotations: list[dict[str, object]] = []@@ -576,7 +591,7 @@ class MarkupProjector:resolved = self.stylesheet.resolve(annotation, style, visibility_hidden)if resolved.subtree_hidden:continue- target = self._figure_annotation_target(annotation, element, visual_blocks_by_child)+ target = annotation_targets.get(annotation)visual_type = _raw_visual_type(target.get("type")) if target is not None else Noneannotation_type = VISUAL_TYPE_MAPPING[visual_type][kind] if visual_type is not None else BlockType.TEXTannotation_blocks: list[dict[str, object]] = []@@ -658,21 +673,28 @@ class MarkupProjector:return blocks, visual_blocks_by_child@staticmethod- def _figure_annotation_target(- annotation: etree._Element,+ def _figure_annotation_targets(figure: etree._Element,+ annotations: set[etree._Element],visual_blocks_by_child: dict[etree._Element, list[dict[str, object]]],- ) -> dict[str, object] | None:- """把 annotation 绑定到最近前序 visual;没有前序时使用最近后序 visual。"""+ ) -> dict[etree._Element, dict[str, object] | None]:+ """用双向线性扫描绑定全部 annotation,优先最近前序 visual。"""children = [child for child in figure if isinstance(child.tag, str)]- position = children.index(annotation)- for child in reversed(children[:position]):+ targets: dict[etree._Element, dict[str, object] | None] = {}+ previous_visual: dict[str, object] | None = None+ for child in children:if visuals := visual_blocks_by_child.get(child):- return visuals[-1]- for child in children[position + 1 :]:+ previous_visual = visuals[-1]+ if child in annotations:+ targets[child] = previous_visual++ next_visual: dict[str, object] | None = None+ for child in reversed(children):if visuals := visual_blocks_by_child.get(child):- return visuals[0]- return None+ next_visual = visuals[0]+ if child in annotations and targets[child] is None:+ targets[child] = next_visual+ return targetsdef _has_contextual_visual_annotation(self, element: etree._Element) -> bool:"""仅在直属完整 token annotation 与 visual 后代并存时启用非标准容器解析。"""@@ -979,8 +1001,7 @@ class MarkupProjector:child_style.text,child_style.visibility_hidden,)- if rendered.strip():- content_parts.append(rendered)+ _append_list_block_content(content_parts, rendered)extras.extend(child_extras)else:rendered, child_extras = self._render_inline_element(child, item_style.text, item_style.visibility_hidden)diff --git a/mineru/model/flash/html/wire.py b/mineru/model/flash/html/wire.pyindex 8691a173..23ab4c01 100644--- a/mineru/model/flash/html/wire.py+++ b/mineru/model/flash/html/wire.py@@ -374,6 +374,8 @@ def _validate_visual_content(content_root: etree._Element, wrapper: etree._Eleme_validate_table_body_shape(child)elif parent_type == BlockType.IMAGE and sub_type == "flowchart":_validate_flowchart_body_shape(child)+ elif parent_type in {BlockType.IMAGE, BlockType.CHART}:+ _validate_owned_visual_image_shape(child, parent_type)for marker in _descendant_markers(child):if marker is child:continue@@ -442,6 +444,23 @@ def _validate_table_body_shape(body: etree._Element) -> None:raise _WireValidationError("invalid_table_body_shape")+def _validate_owned_visual_image_shape(body: etree._Element, parent_type: BlockType) -> None:+ """限制普通图片和图表 body 只能携带一个与父类型匹配的 renderer 图片。"""+ allowed_token = "mineru-image" if parent_type == BlockType.IMAGE else "mineru-chart-image"+ owned_images: list[etree._Element] = []+ for element in body.iterdescendants():+ if not isinstance(element.tag, str) or local_name(element) != "img":+ continue+ owned_tokens = _class_tokens(element) & _OWNED_VISUAL_IMAGE_TOKENS+ if not owned_tokens:+ continue+ if owned_tokens != {allowed_token}:+ raise _WireValidationError("invalid_owned_visual_image_shape")+ owned_images.append(element)+ if len(owned_images) > 1:+ raise _WireValidationError("invalid_owned_visual_image_shape")++def _validate_flowchart_body_shape(body: etree._Element) -> None:"""校验流程图 body 的展示与源码载体,避免精确物化静默丢弃旁路内容。"""_validate_element_only_content(body)diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.pyindex 2844a9bb..1e88e505 100644--- a/tests/unittest/test_flash_html.py+++ b/tests/unittest/test_flash_html.py@@ -17,6 +17,7 @@ from mineru.backend.analyze import aio_doc_analyze, doc_analyzefrom mineru.errors import InvalidRequestErrorfrom mineru.doclib.services.parse_svc import ParseServicefrom mineru.model.flash import HtmlModel+from mineru.model.flash._shared.markup import MarkupProjectorfrom mineru.model.flash.html import HtmlResourceLimitError, HtmlSourceContextfrom mineru.model.flash.html import converter as html_converter_modulefrom mineru.model.flash.html import document as html_document_module@@ -351,8 +352,7 @@ def test_html_auto_selection_precomputes_repeated_candidate_groups(monkeypatch:monkeypatch.setattr(html_selector_module, "_tokens", counted_tokens)items = "".join(- f'<{tag} class="post"><p>{"candidate text " * 16}</p></{tag}>'- for tag in ("div", "section") * (item_count // 2)+ f'<{tag} class="post"><p>{"candidate text " * 16}</p></{tag}>' for tag in ("div", "section") * (item_count // 2))doc_analyze(f"<html><body>{items}</body></html>".encode(), file_suffix="html")@@ -809,6 +809,28 @@ def test_html_interleaved_figure_captions_bind_to_each_nearest_image() -> None:assert [child.content for child in images[1].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption B"]+def test_html_figure_annotation_targets_use_one_batched_scan() -> None:+ """验证大量 figure 说明通过一次批量绑定保持最近前序 visual 关系。"""+ pair_count = 1_000+ figure = etree.Element("figure")+ annotations: set[etree._Element] = set()+ visual_blocks_by_child: dict[etree._Element, list[dict[str, object]]] = {}+ expected_targets: list[dict[str, object]] = []+ for index in range(pair_count):+ image = etree.SubElement(figure, "img")+ visual = {"type": BlockType.IMAGE, "content": "", "index": index}+ visual_blocks_by_child[image] = [visual]+ caption = etree.SubElement(figure, "figcaption")+ annotations.add(caption)+ expected_targets.append(visual)++ targets = MarkupProjector._figure_annotation_targets(figure, annotations, visual_blocks_by_child)++ captions = [child for child in figure if child.tag == "figcaption"]+ assert len(targets) == pair_count+ assert [targets[caption] for caption in captions] == expected_targets++@pytest.mark.parametrize(("visual_markup", "parent_type", "body_type", "annotation_markup", "annotation_type"),[@@ -948,6 +970,19 @@ def test_html_inline_visual_splits_ordered_list_without_renumbering_following_itassert middle.pages[0].blocks[3].content[0].content == "4. Next" # type: ignore[union-attr]+def test_html_list_block_children_keep_semantic_text_boundaries() -> None:+ """验证一个列表项内的多个块级段落不会粘连成错误单词边界。"""+ payload = b"<html><body><ul><li><p>First paragraph.</p><p>Second paragraph.</p></li></ul></body></html>"++ middle, model = doc_analyze(payload, file_suffix="html")+ content = model.pages[0][0]["content"][0]["content"]+ markdown = render_markdown(middle)++ assert content == "First paragraph.\nSecond paragraph."+ assert "First paragraph.Second paragraph." not in markdown+ assert "First paragraph.\nSecond paragraph." in markdown++def test_html_local_base_images_styles_and_escape_are_bounded(tmp_path: Path) -> None:"""验证本地 base、CSS、栅格图可读取,但父目录逃逸图片只保留说明。"""assets = tmp_path / "assets"@@ -1318,6 +1353,62 @@ def test_html_invalid_versioned_markers_fallback_without_partial_results() -> Noassert markdown.count("Visible caption") == 1+ ("parent_type", "body_type", "sub_type", "owned_class"),+ [+ ("image", "image_body", "diagram", "mineru-image"),+ ("chart", "chart_body", "bar", "mineru-chart-image"),+ ],+)+def test_html_versioned_wire_multiple_owned_images_fall_back_without_loss(+ parent_type: str,+ body_type: str,+ sub_type: str,+ owned_class: str,+) -> None:+ """验证普通图片和图表 body 被追加 renderer 图片时回退并保留全部载荷。"""+ source = MiddleJson.model_validate(+ {+ "pages": [+ {+ "page_idx": 0,+ "blocks": [+ {+ "type": parent_type,+ "index": 0,+ "sub_type": sub_type,+ "content": [+ {+ "type": body_type,+ "index": 0,+ "content": "Original visual content",+ "image_url": "https://example.com/original.png",+ }+ ],+ }+ ],+ }+ ],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")+ extra = soup.new_tag(+ "img",+ attrs={"class": owned_class, "src": "https://example.com/added.png", "alt": "Added visual"},+ )+ soup.select_one(f'[data-block-type="{body_type}"]').append(extra)++ _, model = doc_analyze(str(soup).encode(), file_suffix="html")+ image_urls = [str(block["image_url"]) for block in model.pages[0] if block.get("image_url")]++ assert image_urls == ["https://example.com/original.png", "https://example.com/added.png"]++def test_html_versioned_wire_visible_structural_text_falls_back_without_loss() -> None:"""验证机器结构容器中新增的可见文本会整体回退,并保留编辑内容。"""source = MiddleJson.model_validate(