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
refactor: unify content list rendering and add ContentItem dataclass
jinzhenj666c71b99d39
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.pyindex 1d189c08..67525798 100644--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py@@ -5,15 +5,15 @@ from typing import Anyfrom loguru import logger+from ...render.content_list import block_to_content_listfrom ...render.markdown import _get_title_level, blocks_to_markdownfrom ...render.merge import (CJK_LANGS,_collect_text_for_lang_detection,_next_line_starts_with_lowercase_text,_normalize_text_content,- merge_para_text,)-from ...render.merge_visual import _format_embedded_html, _inherit_parent_code_render_metadata, _normalize_visual_content+from ...render.merge_visual import _format_embedded_html, _normalize_visual_contentfrom ...types import BBox, Block, IntBBox, Line, PageInfofrom ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeModefrom ...utils.language import detect_lang@@ -194,140 +194,6 @@ def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:return para_content-def make_blocks_to_content_list(- para_block: Block, img_bucket_path: str, page_idx: int, page_size: tuple[int, int]-) -> dict[str, Any] | None:- para_type = para_block.type- para_content: dict[str, Any] | None = None- if para_type in [- BlockType.TEXT,- BlockType.INDEX,- BlockType.LIST,- BlockType.ABSTRACT,- ]:- para_content = {- "type": ContentType.TEXT,- "text": merge_para_text(para_block),- }- elif para_type in [- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.ASIDE_TEXT,- BlockType.PAGE_FOOTNOTE,- ]:- para_content = {- "type": para_type,- "text": merge_para_text(para_block),- }- elif para_type == BlockType.REF_TEXT:- para_content = {- "type": BlockType.LIST,- "sub_type": BlockType.REF_TEXT,- "list_items": [],- }- for block in _get_ref_text_item_blocks(para_block):- item_text = merge_para_text(block)- if item_text.strip():- para_content["list_items"].append(item_text)- elif para_type == BlockType.TITLE:- para_content = {- "type": ContentType.TEXT,- "text": merge_para_text(para_block),- }- title_level = _get_title_level(para_block)- if title_level != 0:- para_content["text_level"] = title_level- elif para_type == BlockType.INTERLINE_EQUATION:- if len(para_block.lines) == 0 or len(para_block.lines[0].spans) == 0:- return None- para_content = {- "type": ContentType.EQUATION,- "img_path": f"{img_bucket_path}/{para_block.lines[0].spans[0].image_path}",- }- if para_block.lines[0].spans[0].content:- para_content["text"] = merge_para_text(para_block)- para_content["text_format"] = "latex"- elif para_type == BlockType.IMAGE:- para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}- image_path, image_content = _get_body_data(para_block)- if image_path:- para_content["img_path"] = f"{img_bucket_path}/{image_path}"- if image_content:- para_content["content"] = image_content- _apply_visual_sub_type(para_content, para_block)- for block in para_block.blocks:- if block.type == BlockType.IMAGE_BODY:- for line in block.lines:- for span in line.spans:- if span.type == ContentType.IMAGE:- if span.image_path:- para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"- if block.type == BlockType.IMAGE_CAPTION:- para_content[BlockType.IMAGE_CAPTION].append(merge_para_text(block))- if block.type == BlockType.IMAGE_FOOTNOTE:- para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.TABLE:- para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}- for block in para_block.blocks:- if block.type == BlockType.TABLE_BODY:- for line in block.lines:- for span in line.spans:- if span.type == ContentType.TABLE:- if span.html:- para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)- if span.image_path:- para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"-- if block.type == BlockType.TABLE_CAPTION:- para_content[BlockType.TABLE_CAPTION].append(merge_para_text(block))- if block.type == BlockType.TABLE_FOOTNOTE:- para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.CHART:- para_content = {- "type": ContentType.CHART,- "img_path": "",- "content": "",- BlockType.CHART_CAPTION: [],- BlockType.CHART_FOOTNOTE: [],- }- for block in para_block.blocks:- if block.type == BlockType.CHART_BODY:- for line in block.lines:- for span in line.spans:- if span.type == ContentType.CHART and span.image_path:- para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"- if block.type == BlockType.CHART_CAPTION:- para_content[BlockType.CHART_CAPTION].append(merge_para_text(block))- if block.type == BlockType.CHART_FOOTNOTE:- para_content[BlockType.CHART_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.CODE:- para_content = {- "type": BlockType.CODE,- "sub_type": para_block.sub_type,- BlockType.CODE_CAPTION: [],- BlockType.CODE_FOOTNOTE: [],- }- for block in para_block.blocks:- render_block = _inherit_parent_code_render_metadata(block, para_block)- if block.type == BlockType.CODE_BODY:- para_content[BlockType.CODE_BODY] = merge_para_text(render_block)- if block.type == BlockType.CODE_CAPTION:- para_content[BlockType.CODE_CAPTION].append(merge_para_text(block))- if block.type == BlockType.CODE_FOOTNOTE:- para_content[BlockType.CODE_FOOTNOTE].append(merge_para_text(block))-- if not para_content:- return None-- bbox = _build_bbox(para_block.bbox, page_size)- if bbox:- para_content["bbox"] = bbox- para_content["page_idx"] = page_idx-- return para_content--def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: list[int]) -> dict[str, Any] | None:para_type = para_block.typepara_content = None@@ -584,9 +450,9 @@ def union_make(if not para_blocks:continuefor para_block in para_blocks:- para_content = make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)+ para_content = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)if para_content:- output_content_items.append(para_content)+ output_content_items.append(para_content.to_dict())elif make_mode == MakeMode.CONTENT_LIST_V2:para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))page_contents: list[dict[str, Any]] = []diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.pyindex 25f2465c..e095b3b1 100644--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py@@ -4,8 +4,9 @@ from typing import Anyfrom loguru import logger+from ...render.content_list import block_to_content_listfrom ...render.markdown import _get_title_level, blocks_to_markdown-from ...render.merge import _normalize_text_content, merge_para_text+from ...render.merge import _normalize_text_contentfrom ...render.merge_visual import _build_media_path, _format_embedded_htmlfrom ...types import Block, Line, PageInfofrom ...utils.config_reader import get_formula_enable, get_table_enable@@ -36,121 +37,6 @@ def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> Npara_content["sub_type"] = sub_type-def make_blocks_to_content_list(- para_block: Block, img_bucket_path: str, page_idx: int, page_size: tuple[int, int]-) -> dict[str, Any]:- para_type = para_block.type- para_content: dict[str, Any] = {}-- if para_type in [- BlockType.TEXT,- BlockType.REF_TEXT,- BlockType.PHONETIC,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.ASIDE_TEXT,- BlockType.PAGE_FOOTNOTE,- ]:- para_content = {- "type": para_type,- "text": merge_para_text(para_block),- }- elif para_type == BlockType.LIST:- # TODO: Now merge_para_text can handle LIST.- para_content = {- "type": para_type,- "sub_type": para_block.sub_type,- "list_items": [],- }- for block in para_block.blocks:- item_text = merge_para_text(block, escape_text_block_prefix=False)- if item_text.strip():- para_content["list_items"].append(item_text)- elif para_type == BlockType.TITLE:- title_level = _get_title_level(para_block)- para_content = {- "type": ContentType.TEXT,- "text": merge_para_text(para_block),- }- if title_level != 0:- para_content["text_level"] = title_level- elif para_type == BlockType.INTERLINE_EQUATION:- para_content = {- "type": ContentType.EQUATION,- "text": merge_para_text(para_block),- "text_format": "latex",- }- elif para_type == BlockType.IMAGE:- para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}- image_path, image_content = get_body_data(para_block)- para_content["img_path"] = _build_media_path(img_bucket_path, image_path)- para_content["content"] = image_content if image_content else ""- _apply_visual_sub_type(para_content, para_block)- for block in para_block.blocks:- if block.type == BlockType.IMAGE_CAPTION:- para_content[BlockType.IMAGE_CAPTION].append(merge_para_text(block))- if block.type == BlockType.IMAGE_FOOTNOTE:- para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.TABLE:- para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}- for block in para_block.blocks:- if block.type == BlockType.TABLE_BODY:- for line in block.lines:- for span in line.spans:- if span.type == ContentType.TABLE:- if span.html:- para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)- if span.image_path:- para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"-- if block.type == BlockType.TABLE_CAPTION:- para_content[BlockType.TABLE_CAPTION].append(merge_para_text(block))- if block.type == BlockType.TABLE_FOOTNOTE:- para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.CHART:- image_path, chart_content = get_body_data(para_block)- para_content = {- "type": ContentType.CHART,- "img_path": _build_media_path(img_bucket_path, image_path),- "content": chart_content if chart_content else "",- BlockType.CHART_CAPTION: [],- BlockType.CHART_FOOTNOTE: [],- }- _apply_visual_sub_type(para_content, para_block)- for block in para_block.blocks:- if block.type == BlockType.CHART_CAPTION:- para_content[BlockType.CHART_CAPTION].append(merge_para_text(block))- if block.type == BlockType.CHART_FOOTNOTE:- para_content[BlockType.CHART_FOOTNOTE].append(merge_para_text(block))- elif para_type == BlockType.CODE:- para_content = {"type": BlockType.CODE, "sub_type": para_block.sub_type, BlockType.CODE_CAPTION: []}- for block in para_block.blocks:- if block.type == BlockType.CODE_BODY:- code_text = merge_para_text(block)- if para_block.sub_type == BlockType.CODE:- guess_lang = para_block.guess_lang or "txt"- code_text = f"```{guess_lang}\n{code_text}\n```"- para_content[BlockType.CODE_BODY] = code_text- if block.type == BlockType.CODE_CAPTION:- para_content[BlockType.CODE_CAPTION].append(merge_para_text(block))-- page_width, page_height = page_size- para_bbox = para_block.bbox- if para_bbox:- x0, y0, x1, y1 = para_bbox- para_content["bbox"] = [- int(x0 * 1000 / page_width),- int(y0 * 1000 / page_height),- int(x1 * 1000 / page_width),- int(y1 * 1000 / page_height),- ]-- para_content["page_idx"] = page_idx-- return para_content--def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: tuple[int, int]) -> dict:para_type = para_block.typepara_content = {}@@ -516,8 +402,9 @@ def union_make(if not para_blocks:continuefor para_block in para_blocks:- para_content = make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)- output_content.append(para_content)+ para_content = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)+ if para_content is not None:+ output_content.append(para_content.to_dict())elif make_mode == MakeMode.CONTENT_LIST_V2:# https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.mdpara_blocks = (paras_of_layout or []) + (paras_of_discarded or [])diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex 5b91b070..d259e38e 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -17,8 +17,8 @@ from mineru.backend.office.pptx_analyze import office_pptx_analyzefrom mineru.backend.office.xlsx_analyze import office_xlsx_analyzefrom mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyzefrom mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze-from mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.data.data_reader_writer import FileBasedDataWriter+from mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bboxfrom mineru.utils.engine_utils import get_vlm_enginefrom mineru.utils.enum_class import MakeModediff --git a/mineru/model/table/rec/unet_table/utils_table_recover.py b/mineru/model/table/rec/unet_table/utils_table_recover.pyindex fb0ea018..af3fb6ee 100644--- a/mineru/model/table/rec/unet_table/utils_table_recover.py+++ b/mineru/model/table/rec/unet_table/utils_table_recover.py@@ -1,13 +1,11 @@# Copyright (c) Opendatalab. All rights reserved.import re-from typing import Any, Dict, List, Optional, Union, Tuple+from typing import Any, Dict, List, Optional, Tuple, Unionimport numpy as np-def calculate_iou(- box1: Union[np.ndarray, List], box2: Union[np.ndarray, List]-) -> float:+def calculate_iou(box1: Union[np.ndarray, List], box2: Union[np.ndarray, List]) -> float:""":param box1: Iterable [xmin,ymin,xmax,ymax]:param box2: Iterable [xmin,ymin,xmax,ymax]@@ -38,10 +36,7 @@ def calculate_iou(return iou--def is_box_contained(- box1: Union[np.ndarray, List], box2: Union[np.ndarray, List], threshold=0.2-) -> Union[int, None]:+def is_box_contained(box1: Union[np.ndarray, List], box2: Union[np.ndarray, List], threshold=0.2) -> Union[int, None]:""":param box1: Iterable [xmin,ymin,xmax,ymax]:param box2: Iterable [xmin,ymin,xmax,ymax]@@ -63,9 +58,7 @@ def is_box_contained(intersect_y2 = min(b1_y2, b2_y2)# 计算交集的面积- intersect_area = max(0, intersect_x2 - intersect_x1) * max(- 0, intersect_y2 - intersect_y1- )+ intersect_area = max(0, intersect_x2 - intersect_x1) * max(0, intersect_y2 - intersect_y1)# 计算外面的面积b1_outside_area = b1_area - intersect_area@@ -119,9 +112,7 @@ def is_single_axis_contained(return None-def sorted_ocr_boxes(- dt_boxes: Union[np.ndarray, list], threhold: float = 0.2-) -> Tuple[Union[np.ndarray, list], List[int]]:+def sorted_ocr_boxes(dt_boxes: Union[np.ndarray, list], threhold: float = 0.2) -> Tuple[Union[np.ndarray, list], List[int]]:"""Sort text boxes in order from top to bottom, left to rightargs:@@ -143,14 +134,8 @@ def sorted_ocr_boxes(_boxes = np.array(_boxes)for i in range(num_boxes - 1):for j in range(i, -1, -1):- c_idx = is_single_axis_contained(- _boxes[j], _boxes[j + 1], axis="y", threhold=threhold- )- if (- c_idx is not None- and _boxes[j + 1][0] < _boxes[j][0]- and abs(_boxes[j][1] - _boxes[j + 1][1]) < threahold- ):+ c_idx = is_single_axis_contained(_boxes[j], _boxes[j + 1], axis="y", threhold=threhold)+ if c_idx is not None and _boxes[j + 1][0] < _boxes[j][0] and abs(_boxes[j][1] - _boxes[j + 1][1]) < threahold:_boxes[j], _boxes[j + 1] = _boxes[j + 1].copy(), _boxes[j].copy()indices[j], indices[j + 1] = indices[j + 1], indices[j]else:@@ -196,10 +181,7 @@ def _pred_boxes_to_array(pred_bboxes: np.ndarray) -> np.ndarray:if pred_bboxes.size == 0:return np.empty((0, 4), dtype=np.float64)return np.asarray(- [- [pred_box[0][0], pred_box[0][1], pred_box[2][0], pred_box[2][1]]- for pred_box in pred_bboxes- ],+ [[pred_box[0][0], pred_box[0][1], pred_box[2][0], pred_box[2][1]] for pred_box in pred_bboxes],dtype=np.float64,)@@ -349,9 +331,7 @@ def _same_row_adjacent_cells(candidate_boxes: List[np.ndarray]) -> bool:return Falsefor left_box, right_box in zip(candidate_boxes, candidate_boxes[1:]):- y_overlap = min(float(left_box[3]), float(right_box[3])) - max(- float(left_box[1]), float(right_box[1])- )+ y_overlap = min(float(left_box[3]), float(right_box[3])) - max(float(left_box[1]), float(right_box[1]))min_height = min(float(left_box[3] - left_box[1]),float(right_box[3] - right_box[1]),@@ -517,9 +497,7 @@ def match_ocr_cell(dt_rec_boxes: List[List[Union[Any, str]]], pred_bboxes: np.ndprojection_indices = np.flatnonzero(projection_mask[i])if len(projection_indices) > 1:min_segment_width = _min_projection_segment_width(str(gt_box[1]), ocr_boxes[i])- projection_indices = projection_indices[- inter_width[i][projection_indices] >= min_segment_width- ]+ projection_indices = projection_indices[inter_width[i][projection_indices] >= min_segment_width]split_results = _split_cross_cell_ocr_result(gt_box,ocr_boxes[i],@@ -581,9 +559,7 @@ def gather_ocr_list_by_row(ocr_list: List[Any], threhold: float = 0.2) -> List[Anext = ocr_list[j]cur_box = cur[0]next_box = next[0]- c_idx = is_single_axis_contained(- cur[0], next[0], axis="y", threhold=threhold- )+ c_idx = is_single_axis_contained(cur[0], next[0], axis="y", threhold=threhold)if c_idx:dis = max(next_box[0] - cur_box[2], 0)blank_str = int(dis / threshold) * " "@@ -619,17 +595,13 @@ def _normalize_cell_text_map(cell_box_map: Dict[int, List[str]]) -> Dict[int, Linormalized[int(cell_idx)] = [values]continuetry:- normalized[int(cell_idx)] = [- str(value) for value in values if value is not None- ]+ normalized[int(cell_idx)] = [str(value) for value in values if value is not None]except TypeError:normalized[int(cell_idx)] = [str(values)]return normalized-def _normalize_cell_bboxes(- cell_bboxes: Optional[Union[np.ndarray, List]]-) -> Optional[np.ndarray]:+def _normalize_cell_bboxes(cell_bboxes: Optional[Union[np.ndarray, List]]) -> Optional[np.ndarray]:"""把单元格物理框统一成 N x 4 x 2,用于判断边缘空列是否是结构噪声。"""if cell_bboxes is None:return None@@ -719,29 +691,18 @@ def _estimate_axis_sizes(for axis_idx in target_range:if 0 <= axis_idx < axis_count:axis_sizes[axis_idx].append(size)- return [- float(np.median(sizes)) if sizes else None- for sizes in axis_sizes- ]+ return [float(np.median(sizes)) if sizes else None for sizes in axis_sizes]-def _axis_reference_size(- axis_sizes: List[Optional[float]], axis_idx: int-) -> Optional[float]:+def _axis_reference_size(axis_sizes: List[Optional[float]], axis_idx: int) -> Optional[float]:"""用其它行/列的中位尺寸作为参照,避免单个边缘噪声框主导判断。"""- sizes = [- size- for i, size in enumerate(axis_sizes)- if i != axis_idx and size is not None and size > 0- ]+ sizes = [size for i, size in enumerate(axis_sizes) if i != axis_idx and size is not None and size > 0]if not sizes:return Nonereturn float(np.median(sizes))-def _axis_size_is_abnormal(- axis_sizes: List[Optional[float]], axis_idx: int-) -> bool:+def _axis_size_is_abnormal(axis_sizes: List[Optional[float]], axis_idx: int) -> bool:"""判断空边缘行/列尺寸是否明显异常;正常尺寸的完整空列需要保留。"""axis_size = axis_sizes[axis_idx]reference_size = _axis_reference_size(axis_sizes, axis_idx)@@ -766,10 +727,7 @@ def _edge_axis_has_text(positions = (grid[row][axis_idx] for row in range(row_start, row_end + 1))else:positions = (grid[axis_idx][col] for col in range(col_start, col_end + 1))- return any(- cell is not None and _cell_has_visible_text(cell_text_map, cell[0])- for cell in positions- )+ return any(cell is not None and _cell_has_visible_text(cell_text_map, cell[0]) for cell in positions)def _edge_axis_coverage(@@ -783,16 +741,10 @@ def _edge_axis_coverage() -> Tuple[int, int]:"""统计边缘行/列在当前保留范围内的结构覆盖度,覆盖不完整通常是外围噪声。"""if axis == "col":- covered = sum(- grid[row][axis_idx] is not None- for row in range(row_start, row_end + 1)- )+ covered = sum(grid[row][axis_idx] is not None for row in range(row_start, row_end + 1))total = row_end - row_start + 1else:- covered = sum(- grid[axis_idx][col] is not None- for col in range(col_start, col_end + 1)- )+ covered = sum(grid[axis_idx][col] is not None for col in range(col_start, col_end + 1))total = col_end - col_start + 1return covered, total@@ -809,13 +761,9 @@ def _is_noise_edge_axis(col_end: int,) -> bool:"""只裁剪无文本且结构不完整或尺寸异常的边缘,保留真实完整空行/空列。"""- if _edge_axis_has_text(- grid, cell_text_map, axis, axis_idx, row_start, row_end, col_start, col_end- ):+ if _edge_axis_has_text(grid, cell_text_map, axis, axis_idx, row_start, row_end, col_start, col_end):return False- covered, total = _edge_axis_coverage(- grid, axis, axis_idx, row_start, row_end, col_start, col_end- )+ covered, total = _edge_axis_coverage(grid, axis, axis_idx, row_start, row_end, col_start, col_end)if covered == 0 or covered < total:return Truereturn _axis_size_is_abnormal(axis_sizes, axis_idx)@@ -834,23 +782,19 @@ def _trim_noise_edges(col_start, col_end = 0, max_col - 1while row_start <= row_end and _is_noise_edge_axis(- grid, cell_text_map, row_sizes, "row", row_start,- row_start, row_end, col_start, col_end,+ grid, cell_text_map, row_sizes, "row", row_start, row_start, row_end, col_start, col_end):row_start += 1while row_end >= row_start and _is_noise_edge_axis(- grid, cell_text_map, row_sizes, "row", row_end,- row_start, row_end, col_start, col_end,+ grid, cell_text_map, row_sizes, "row", row_end, row_start, row_end, col_start, col_end):row_end -= 1while col_start <= col_end and _is_noise_edge_axis(- grid, cell_text_map, col_sizes, "col", col_start,- row_start, row_end, col_start, col_end,+ grid, cell_text_map, col_sizes, "col", col_start, row_start, row_end, col_start, col_end):col_start += 1while col_end >= col_start and _is_noise_edge_axis(- grid, cell_text_map, col_sizes, "col", col_end,- row_start, row_end, col_start, col_end,+ grid, cell_text_map, col_sizes, "col", col_end, row_start, row_end, col_start, col_end):col_end -= 1@@ -871,9 +815,7 @@ def plot_html_table(grid, max_row, max_col = _build_table_grid(logic_points)row_sizes = _estimate_axis_sizes(logic_points, normalized_bboxes, "row", max_row)col_sizes = _estimate_axis_sizes(logic_points, normalized_bboxes, "col", max_col)- row_start, row_end, col_start, col_end = _trim_noise_edges(- grid, cell_text_map, row_sizes, col_sizes, max_row, max_col- )+ row_start, row_end, col_start, col_end = _trim_noise_edges(grid, cell_text_map, row_sizes, col_sizes, max_row, max_col)table_html = "<html><body><table>"if row_start > row_end or col_start > col_end:@@ -894,7 +836,9 @@ def plot_html_table(row_span = min(origin_row_end, row_end) - clipped_row_start + 1col_span = min(origin_col_end, col_end) - clipped_col_start + 1text = _cell_text(cell_text_map, cell_idx)- temp += f"<td rowspan={row_span} colspan={col_span}>{text}</td>"+ row_span_str = f" rowspan={row_span}" if row_span > 1 else ""+ col_span_str = f" colspan={col_span}" if col_span > 1 else ""+ temp += f"<td{row_span_str}{col_span_str}>{text}</td>"table_html = table_html + temp + "</tr>"table_html += "</table></body></html>"diff --git a/mineru/render/content_list.py b/mineru/render/content_list.pynew file mode 100644index 00000000..f781e27b--- /dev/null+++ b/mineru/render/content_list.py@@ -0,0 +1,166 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++from ..types import EMPTY_BBOX, BBox, Block, ContentItem, IntBBox+from ..utils.enum_class import BlockType, ContentType+from .markdown import _build_media_path, _get_title_level+from .merge import _merge_para_text, merge_para_text+from .merge_visual import _format_embedded_html, _inherit_parent_code_render_metadata, _normalize_visual_content+++def block_to_content_list(+ para_block: Block,+ img_bucket_path: str,+ page_idx: int,+ page_size: tuple[int, int] | None,+) -> ContentItem | None:+ para_type = para_block.type+ if para_type in [+ BlockType.TEXT,+ BlockType.PHONETIC,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.ASIDE_TEXT,+ BlockType.PAGE_FOOTNOTE,+ ]:+ item = ContentItem(+ type=para_type,+ text=merge_para_text(para_block),+ )+ elif para_type in [BlockType.INDEX, BlockType.ABSTRACT]:+ item = ContentItem(+ type=ContentType.TEXT,+ text=merge_para_text(para_block),+ )+ elif para_type == BlockType.LIST:+ if para_block.blocks:+ # Some LayoutModel use LIST as a container.+ item = ContentItem(type=para_type, sub_type=para_block.sub_type or None)+ for block in para_block.blocks:+ if (item_text := _merge_para_text(block)).strip():+ item.list_items.append(item_text)+ else:+ item = ContentItem(+ type=ContentType.TEXT,+ text=merge_para_text(para_block),+ )+ elif para_type == BlockType.REF_TEXT:+ if para_block.blocks:+ item = ContentItem(type=BlockType.LIST, sub_type=BlockType.REF_TEXT)+ for block in para_block.blocks:+ if (item_text := _merge_para_text(block)).strip():+ item.list_items.append(item_text)+ else:+ item = ContentItem(+ type=para_type,+ text=merge_para_text(para_block),+ )+ elif para_type == BlockType.TITLE:+ title_level = _get_title_level(para_block)+ item = ContentItem(+ type=ContentType.TEXT,+ text=merge_para_text(para_block),+ text_level=title_level if title_level != 0 else None,+ )+ elif para_type == BlockType.INTERLINE_EQUATION:+ item = ContentItem(+ type=ContentType.EQUATION,+ img_path=_body_data(para_block, img_bucket_path)[0],+ text=merge_para_text(para_block),+ text_format="latex",+ )+ elif para_type == BlockType.IMAGE:+ item = ContentItem(+ type=ContentType.IMAGE,+ sub_type=para_block.sub_type or None,+ )+ for block in para_block.blocks:+ if block.type == BlockType.IMAGE_BODY:+ item.img_path, item.content = _body_data(block, img_bucket_path)+ if block.type == BlockType.IMAGE_CAPTION:+ item.image_caption.append(merge_para_text(block))+ if block.type == BlockType.IMAGE_FOOTNOTE:+ item.image_footnote.append(merge_para_text(block))+ elif para_type == BlockType.TABLE:+ item = ContentItem(type=ContentType.TABLE)+ for block in para_block.blocks:+ if block.type == BlockType.TABLE_BODY:+ item.img_path, item.table_body = _body_data(block, img_bucket_path)+ if block.type == BlockType.TABLE_CAPTION:+ item.table_caption.append(merge_para_text(block))+ if block.type == BlockType.TABLE_FOOTNOTE:+ item.table_footnote.append(merge_para_text(block))+ elif para_type == BlockType.CHART:+ item = ContentItem(+ type=ContentType.CHART,+ sub_type=para_block.sub_type or None,+ )+ for block in para_block.blocks:+ if block.type == BlockType.CHART_BODY:+ item.img_path, item.content = _body_data(block, img_bucket_path)+ if block.type == BlockType.CHART_CAPTION:+ item.chart_caption.append(merge_para_text(block))+ if block.type == BlockType.CHART_FOOTNOTE:+ item.chart_footnote.append(merge_para_text(block))+ elif para_type == BlockType.CODE:+ item = ContentItem(+ type=BlockType.CODE,+ sub_type=para_block.sub_type or None,+ )+ for block in para_block.blocks:+ if block.type == BlockType.CODE_BODY:+ render_block = _inherit_parent_code_render_metadata(block, para_block)+ item.code_body = merge_para_text(render_block)+ if block.type == BlockType.CODE_CAPTION:+ item.code_caption.append(merge_para_text(block))+ if block.type == BlockType.CODE_FOOTNOTE:+ item.code_footnote.append(merge_para_text(block))+ else:+ return None++ item.page_idx = page_idx+ if bbox := _norm1k_bbox(para_block.bbox, page_size):+ item.bbox = bbox+ return item+++def _body_data(para_block: Block, img_bucket_path: str) -> tuple[str, str]:+ image_path, content = "", ""+ for span in (+ span+ for block in para_block.blocks or [para_block]+ if block.type+ in [+ BlockType.IMAGE_BODY,+ BlockType.TABLE_BODY,+ BlockType.CHART_BODY,+ BlockType.INTERLINE_EQUATION,+ ]+ for line in block.lines+ for span in line.spans+ ):+ if span.type == ContentType.IMAGE:+ image_path, content = span.image_path, _normalize_visual_content(span.content)+ elif span.type == ContentType.TABLE:+ image_path, content = span.image_path, _format_embedded_html(span.html, img_bucket_path)+ elif span.type == ContentType.CHART:+ image_path, content = span.image_path, span.content+ elif span.type == ContentType.INTERLINE_EQUATION:+ image_path, content = span.image_path, span.content+ if image_path or content:+ break+ return _build_media_path(img_bucket_path, image_path), content+++def _norm1k_bbox(para_bbox: BBox, page_size: tuple[int, int] | None) -> IntBBox | None:+ if para_bbox == EMPTY_BBOX or not page_size:+ return None+ page_width, page_height = page_size+ x0, y0, x1, y1 = para_bbox+ return (+ int(x0 * 1000 / page_width),+ int(y0 * 1000 / page_height),+ int(x1 * 1000 / page_width),+ int(y1 * 1000 / page_height),+ )diff --git a/mineru/render/union_make.py b/mineru/render/union_make.pyindex 1f82ff94..2b704dfc 100644--- a/mineru/render/union_make.py+++ b/mineru/render/union_make.py@@ -27,19 +27,18 @@ def _dispatch_make_content_list(img_bucket_path: str,page_idx: int,page_size: Any,-) -> Any: # type: ignore[return]- if backend == "pipeline":- from ..backend.pipeline.pipeline_middle_json_mkcontent import make_blocks_to_content_list-- return make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)+) -> Any:if backend == "office":from ..backend.office.mkcontent.output_builders import make_blocks_to_content_listreturn make_blocks_to_content_list(para_block, img_bucket_path, page_idx)- # vlm / hybrid- from ..backend.vlm.vlm_middle_json_mkcontent import make_blocks_to_content_list- return make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)+ from ..render.content_list import block_to_content_list++ item = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)+ if item is None:+ return None+ return item.to_dict(skip_defaults=True)def _dispatch_make_content_list_v2(@@ -47,7 +46,7 @@ def _dispatch_make_content_list_v2(para_block: Any,img_bucket_path: str,page_size: Any,-) -> Any: # type: ignore[return]+) -> Any:if backend == "pipeline":from ..backend.pipeline.pipeline_middle_json_mkcontent import make_blocks_to_content_list_v2diff --git a/mineru/types.py b/mineru/types.pyindex 68995160..af2ab0f0 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -1,7 +1,7 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-from dataclasses import dataclass, field, fields+from dataclasses import MISSING, Field, dataclass, field, fieldsfrom typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hintsT = TypeVar("T", bound="_DocElement")@@ -304,6 +304,15 @@ VISUAL_TYPE_MAPPING = {BBox: TypeAlias = tuple[float, float, float, float]IntBBox: TypeAlias = tuple[int, int, int, int]++def _is_default_value(f: Field, value: Any) -> bool:+ if f.default is not MISSING:+ return value == f.default+ if f.default_factory is not MISSING:+ return value == f.default_factory()+ return False++EMPTY_BBOX: BBox = (0.0, 0.0, 0.0, 0.0)@@ -320,15 +329,21 @@ def _list_arg(tp: Any) -> Any | None:class _DocElement:"""Base class for document-model nodes (Span, Line, Block, PageInfo)."""- def to_dict(self) -> dict[str, Any]:- """Serialize to dict, excluding private fields (prefixed with ``_``). Nested dataclass lists are recursed."""+ def to_dict(self, *, skip_defaults: bool = False) -> dict[str, Any]:+ """Serialize to dict, excluding private fields (prefixed with ``_``).++ When *skip_defaults* is True, fields whose value equals their+ default are also omitted.+ """result: dict[str, Any] = {}for f in fields(self):if f.name.startswith("_"):continuevalue = getattr(self, f.name)+ if skip_defaults and _is_default_value(f, value):+ continueif isinstance(value, list):- result[f.name] = [v.to_dict() if isinstance(v, _DocElement) else v for v in value]+ result[f.name] = [v.to_dict(skip_defaults=skip_defaults) if isinstance(v, _DocElement) else v for v in value]else:result[f.name] = valuereturn result@@ -456,3 +471,29 @@ class PageInfo(_DocElement):# Temporary — will be removed once the render layer converges._backend: Literal["pipeline", "vlm", "hybrid", "office"] | None = None+++@dataclass+class ContentItem(_DocElement):+ """A single item in the Content List (V1) output format."""++ type: str+ page_idx: int = 0+ bbox: IntBBox | None = None+ text: str | None = None+ text_level: int | None = None+ text_format: str | None = None+ img_path: str | None = None+ content: str | None = None+ sub_type: str | None = None+ list_items: list[str] = field(default_factory=list)+ image_caption: list[str] = field(default_factory=list)+ image_footnote: list[str] = field(default_factory=list)+ table_caption: list[str] = field(default_factory=list)+ table_footnote: list[str] = field(default_factory=list)+ table_body: str | None = None+ chart_caption: list[str] = field(default_factory=list)+ chart_footnote: list[str] = field(default_factory=list)+ code_caption: list[str] = field(default_factory=list)+ code_footnote: list[str] = field(default_factory=list)+ code_body: str | None = None