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
work review
Sidney2337387797b17c3
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex 735b37b8..45e5486a 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -18,6 +18,9 @@ from markdown_it.common.html_re import attributefrom markdown_it.rules_block import list_blockfrom pydantic import AnyUrl+from mineru.model.utils.docx.mammoth import body_xml+from mineru.model.utils.docx.mammoth.conversion import convert_document_element_to_html+from mineru.model.utils.docx.mammoth.office_xml import read_strfrom mineru.model.utils.docx.math.omml import oMath2Latexfrom mineru.utils.docx_fomatting import Formatting, Scriptfrom mineru.utils.enum_class import BlockType, ContentType@@ -145,14 +148,13 @@ class DocxConverter:)if tag_name == "tbl":- pass- # try:- # # 处理表格元素- # t = self._handle_tables(element)- # added_elements.extend(t)- # except Exception:- # # 如果表格解析失败,记录调试信息- # _log.debug("could not parse a table, broken docx table")+ try:+ # 处理表格元素+ t = self._handle_tables(element)+ added_elements.extend(t)+ except Exception:+ # 如果表格解析失败,记录调试信息+ _log.debug("could not parse a table, broken docx table")# 检查图片元素elif drawing_blip:# 处理图片元素@@ -181,6 +183,30 @@ class DocxConverter:else:_log.debug(f"Ignoring element in DOCX with tag: {tag_name}")+ def _handle_tables(self, element: BaseOxmlElement):+ """+ 处理表格。++ Args:+ element: 元素对象+ Returns:+ list[RefItem]: 元素引用列表+ """+ elem_ref = []+ table = read_str(element.xml)+ body_reader = body_xml.reader()+ t = body_reader.read_all([table])+ res = convert_document_element_to_html(t.value[0])+ table_block = {+ "image_source": "",+ "html": res.value,+ "table_caption": "",+ "table_footnote": "",+ "table_type": "",+ "table_nest_level": "",+ }+ self.blocks.append(table_block)+def _handle_text_elements(self,element: BaseOxmlElement,@@ -234,11 +260,11 @@ class DocxConverter:elem_ref.extend(li) # 必须是引用!!!# self._update_history(p_style_id, p_level, numid, ilevel)return elem_ref- elif ( # 列表结束处理- numid is None- and self.pre_num_id != -1- and p_style_id not in ["Title", "Heading"]- ):# 关闭列表+ elif ( # 列表结束处理+ numid is None+ and self.pre_num_id != -1+ and p_style_id not in ["Title", "Heading"]+ ): # 关闭列表# 重置列表状态self.pre_num_id = -1self.pre_ilevel = -1@@ -934,6 +960,9 @@ class DocxConverter:"list_type": "text_list","ilevel": ilevel,}+ # 增加目前栈内的 nest level+ for block in self.list_block_stack:+ block["list_nest_level"] += 1# 获取栈顶的列表块parent_list_block = self.list_block_stack[-1]# 将新列表块添加为父列表块的最新列表项的子块diff --git a/mineru/model/docx/main.py b/mineru/model/docx/main.pyindex 911b6261..b795ce18 100644--- a/mineru/model/docx/main.py+++ b/mineru/model/docx/main.py@@ -15,4 +15,4 @@ def convert_binary(file_binary: BinaryIO, file_path: str):if __name__ == "__main__":- print(convert_path("test.docx"))\ No newline at end of file+ print(convert_path("testbak.docx"))\ No newline at end of filediff --git a/mineru/model/utils/docx/mammoth/__init__.py b/mineru/model/utils/docx/mammoth/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/mineru/model/utils/docx/mammoth/body_xml.py b/mineru/model/utils/docx/mammoth/body_xml.pynew file mode 100644index 00000000..65900cff--- /dev/null+++ b/mineru/model/utils/docx/mammoth/body_xml.py@@ -0,0 +1,810 @@+import contextlib+import re+import sys+from . import documents+from . import results+from . import lists+from . import transforms+from . import complex_fields+from . import dingbats+from .xmlparser import node_types, XmlElement, null_xml_element+from .styles_xml import Styles+from .uris import replace_fragment, uri_to_zip_entry_name++if sys.version_info >= (3, ):+ unichr = chr+++def reader(+ numbering=None,+ content_types=None,+ relationships=None,+ styles=None,+ docx_file=None,+ files=None+):++ if styles is None:+ styles = Styles.EMPTY++ read_all = _create_reader(+ numbering=numbering,+ content_types=content_types,+ relationships=relationships,+ styles=styles,+ docx_file=docx_file,+ files=files,+ )+ return _BodyReader(read_all)++++class _BodyReader(object):+ def __init__(self, read_all):+ self._read_all = read_all++ def read_all(self, elements):+ result = self._read_all(elements)+ return results.Result(result.elements, result.messages)+++def _create_reader(numbering, content_types, relationships, styles, docx_file, files):+ current_instr_text = []+ complex_field_stack = []++ # When a paragraph is marked as deleted, its contents should be combined+ # with the following paragraph. See 17.13.5.15 del (Deleted Paragraph) of+ # ECMA-376 4th edition Part 1.+ deleted_paragraph_contents = []++ _ignored_elements = set([+ "office-word:wrap",+ "v:shadow",+ "v:shapetype",+ "w:annotationRef",+ "w:bookmarkEnd",+ "w:sectPr",+ "w:proofErr",+ "w:lastRenderedPageBreak",+ "w:commentRangeStart",+ "w:commentRangeEnd",+ "w:del",+ "w:footnoteRef",+ "w:endnoteRef",+ "w:pPr",+ "w:rPr",+ "w:tblPr",+ "w:tblGrid",+ "w:trPr",+ "w:tcPr",+ ])++ def text(element):+ return _success(documents.Text(_inner_text(element)))++ def run(element):+ properties = element.find_child_or_null("w:rPr")+ vertical_alignment = properties \+ .find_child_or_null("w:vertAlign") \+ .attributes.get("w:val")+ font = properties.find_child_or_null("w:rFonts").attributes.get("w:ascii")++ font_size_string = properties.find_child_or_null("w:sz").attributes.get("w:val")+ if _is_int(font_size_string):+ # w:sz gives the font size in half points, so halve the value to get the size in points+ font_size = int(font_size_string) / 2+ else:+ font_size = None++ is_bold = read_boolean_element(properties.find_child("w:b"))+ is_italic = read_boolean_element(properties.find_child("w:i"))+ is_underline = read_underline_element(properties.find_child("w:u"))+ is_strikethrough = read_boolean_element(properties.find_child("w:strike"))+ is_all_caps = read_boolean_element(properties.find_child("w:caps"))+ is_small_caps = read_boolean_element(properties.find_child("w:smallCaps"))+ highlight = read_highlight_value(properties.find_child_or_null("w:highlight").attributes.get("w:val"))++ def add_complex_field_hyperlink(children):+ hyperlink_kwargs = current_hyperlink_kwargs()+ if hyperlink_kwargs is None:+ return children+ else:+ return [documents.hyperlink(children=children, **hyperlink_kwargs)]++ return _ReadResult.map_results(+ _read_run_style(properties),+ _read_xml_elements(element.children).map(add_complex_field_hyperlink),+ lambda style, children: documents.run(+ children=children,+ style_id=style[0],+ style_name=style[1],+ is_bold=is_bold,+ is_italic=is_italic,+ is_underline=is_underline,+ is_strikethrough=is_strikethrough,+ is_all_caps=is_all_caps,+ is_small_caps=is_small_caps,+ vertical_alignment=vertical_alignment,+ font=font,+ font_size=font_size,+ highlight=highlight,+ ))++ def _read_run_style(properties):+ return _read_style(properties, "w:rStyle", "Run", styles.find_character_style_by_id)++ def read_boolean_element(element):+ if element is None:+ return False+ else:+ return read_boolean_attribute_value(element.attributes.get("w:val"))++ def read_boolean_attribute_value(value):+ return value not in ["false", "0"]++ def read_underline_element(element):+ return element and element.attributes.get("w:val") not in [None, "false", "0", "none"]++ def read_highlight_value(value):+ if not value or value == "none":+ return None+ else:+ return value++ def paragraph(element):+ properties = element.find_child_or_null("w:pPr")++ is_deleted = properties.find_child_or_null("w:rPr").find_child("w:del")++ if is_deleted is not None:+ for child in element.children:+ deleted_paragraph_contents.append(child)+ return _empty_result++ else:+ alignment = properties.find_child_or_null("w:jc").attributes.get("w:val")+ indent = _read_paragraph_indent(properties.find_child_or_null("w:ind"))++ children_xml = element.children+ if deleted_paragraph_contents:+ children_xml = deleted_paragraph_contents + children_xml+ del deleted_paragraph_contents[:]++ return _ReadResult.map_results(+ _read_paragraph_style(properties),+ _read_xml_elements(children_xml),+ lambda style, children: documents.paragraph(+ children=children,+ style_id=style[0],+ style_name=style[1],+ numbering=_read_numbering_properties(+ paragraph_style_id=style[0],+ element=properties.find_child_or_null("w:numPr"),+ ),+ alignment=alignment,+ indent=indent,+ )).append_extra()++ def _read_paragraph_style(properties):+ return _read_style(properties, "w:pStyle", "Paragraph", styles.find_paragraph_style_by_id)++ def current_hyperlink_kwargs():+ for complex_field in reversed(complex_field_stack):+ if isinstance(complex_field, complex_fields.Hyperlink):+ return complex_field.kwargs++ return None++ def read_fld_char(element):+ fld_char_type = element.attributes.get("w:fldCharType")+ if fld_char_type == "begin":+ complex_field_stack.append(complex_fields.begin(fld_char=element))+ del current_instr_text[:]++ elif fld_char_type == "end":+ complex_field = complex_field_stack.pop()+ if isinstance(complex_field, complex_fields.Begin):+ complex_field = parse_current_instr_text(complex_field)++ if isinstance(complex_field, complex_fields.Checkbox):+ return _success(documents.checkbox(checked=complex_field.checked))++ elif fld_char_type == "separate":+ complex_field_separate = complex_field_stack.pop()+ complex_field = parse_current_instr_text(complex_field_separate)+ complex_field_stack.append(complex_field)++ return _empty_result++ def parse_current_instr_text(complex_field):+ instr_text = "".join(current_instr_text)++ if isinstance(complex_field, complex_fields.Begin):+ fld_char = complex_field.fld_char+ else:+ fld_char = null_xml_element++ return parse_instr_text(instr_text, fld_char=fld_char)++ def parse_instr_text(instr_text, *, fld_char):+ external_link_result = re.match(r'\s*HYPERLINK "(.*)"', instr_text)+ if external_link_result is not None:+ return complex_fields.hyperlink(dict(href=external_link_result.group(1)))++ internal_link_result = re.match(r'\s*HYPERLINK\s+\\l\s+"(.*)"', instr_text)+ if internal_link_result is not None:+ return complex_fields.hyperlink(dict(anchor=internal_link_result.group(1)))++ checkbox_result = re.match(r'\s*FORMCHECKBOX\s*', instr_text)+ if checkbox_result is not None:+ checkbox_element = fld_char \+ .find_child_or_null("w:ffData") \+ .find_child_or_null("w:checkBox")+ checked_element = checkbox_element.find_child("w:checked")++ if checked_element is None:+ checked = read_boolean_element(checkbox_element.find_child("w:default"))+ else:+ checked = read_boolean_element(checked_element)++ return complex_fields.checkbox(checked=checked)++ return None++ def read_instr_text(element):+ current_instr_text.append(_inner_text(element))+ return _empty_result++ def _read_style(properties, style_tag_name, style_type, find_style_by_id):+ messages = []+ style_id = properties \+ .find_child_or_null(style_tag_name) \+ .attributes.get("w:val")++ if style_id is None:+ style_name = None+ else:+ style = find_style_by_id(style_id)+ if style is None:+ style_name = None+ messages.append(_undefined_style_warning(style_type, style_id))+ else:+ style_name = style.name++ return _ReadResult([style_id, style_name], [], messages)++ def _undefined_style_warning(style_type, style_id):+ return results.warning("{0} style with ID {1} was referenced but not defined in the document".format(style_type, style_id))++ def _read_numbering_properties(paragraph_style_id, element):+ num_id = element.find_child_or_null("w:numId").attributes.get("w:val")+ level_index = element.find_child_or_null("w:ilvl").attributes.get("w:val")+ if num_id is not None and level_index is not None:+ return numbering.find_level(num_id, level_index)++ if paragraph_style_id is not None:+ level = numbering.find_level_by_paragraph_style_id(paragraph_style_id)+ if level is not None:+ return level++ # Some malformed documents define numbering levels without an index, and+ # reference the numbering using a w:numPr element without a w:ilvl child.+ # To handle such cases, we assume a level of 0 as a fallback.+ if num_id is not None:+ return numbering.find_level(num_id, "0")++ return None++ def _read_paragraph_indent(element):+ attributes = element.attributes+ return documents.paragraph_indent(+ start=attributes.get("w:start") or attributes.get("w:left"),+ end=attributes.get("w:end") or attributes.get("w:right"),+ first_line=attributes.get("w:firstLine"),+ hanging=attributes.get("w:hanging"),+ )++ def tab(element):+ return _success(documents.tab())+++ def no_break_hyphen(element):+ return _success(documents.text(unichr(0x2011)))+++ def soft_hyphen(element):+ return _success(documents.text(u"\u00ad"))++ def symbol(element):+ # See 17.3.3.30 sym (Symbol Character) of ECMA-376 4th edition Part 1+ font = element.attributes.get("w:font")+ char = element.attributes.get("w:char")++ unicode_code_point = dingbats.get((font, int(char, 16)))++ if unicode_code_point is None and re.match("^F0..", char):+ unicode_code_point = dingbats.get((font, int(char[2:], 16)))++ if unicode_code_point is None:+ warning = results.warning("A w:sym element with an unsupported character was ignored: char {0} in font {1}".format(+ char,+ font,+ ))+ return _empty_result_with_message(warning)+ else:+ return _success(documents.text(unichr(unicode_code_point)))+++ def table(element):+ properties = element.find_child_or_null("w:tblPr")+ return _ReadResult.map_results(+ read_table_style(properties),+ _read_xml_elements(element.children)+ .flat_map(calculate_row_spans),++ lambda style, children: documents.table(+ children=children,+ style_id=style[0],+ style_name=style[1],+ ),+ )+++ def read_table_style(properties):+ return _read_style(properties, "w:tblStyle", "Table", styles.find_table_style_by_id)+++ def table_row(element):+ properties = element.find_child_or_null("w:trPr")++ # See 17.13.5.12 del (Deleted Table Row) of ECMA-376 4th edition Part 1+ is_deleted = bool(properties.find_child("w:del"))+ if is_deleted:+ return _empty_result++ is_header = bool(properties.find_child("w:tblHeader"))+ return _read_xml_elements(element.children) \+ .map(lambda children: documents.table_row(+ children=children,+ is_header=is_header,+ ))+++ def table_cell(element):+ properties = element.find_child_or_null("w:tcPr")+ gridspan = properties \+ .find_child_or_null("w:gridSpan") \+ .attributes.get("w:val")++ if gridspan is None:+ colspan = 1+ else:+ colspan = int(gridspan)++ return _read_xml_elements(element.children) \+ .map(lambda children: documents.table_cell_unmerged(+ children=children,+ colspan=colspan,+ rowspan=1,+ vmerge=read_vmerge(properties),+ ))++ def read_vmerge(properties):+ vmerge_element = properties.find_child("w:vMerge")+ if vmerge_element is None:+ return False+ else:+ val = vmerge_element.attributes.get("w:val")+ return val == "continue" or not val+++ def calculate_row_spans(rows):+ unexpected_non_rows = any(+ not isinstance(row, documents.TableRow)+ for row in rows+ )+ if unexpected_non_rows:+ rows = remove_unmerged_table_cells(rows)+ return _elements_result_with_messages(rows, [results.warning(+ "unexpected non-row element in table, cell merging may be incorrect"+ )])++ unexpected_non_cells = any(+ not isinstance(cell, documents.TableCellUnmerged)+ for row in rows+ for cell in row.children+ )+ if unexpected_non_cells:+ rows = remove_unmerged_table_cells(rows)+ return _elements_result_with_messages(rows, [results.warning(+ "unexpected non-cell element in table row, cell merging may be incorrect"+ )])++ columns = {}+ for row in rows:+ cell_index = 0+ for cell in row.children:+ if cell.vmerge and cell_index in columns:+ columns[cell_index].rowspan += 1+ else:+ columns[cell_index] = cell+ cell.vmerge = False+ cell_index += cell.colspan++ for row in rows:+ row.children = [+ documents.table_cell(+ children=cell.children,+ colspan=cell.colspan,+ rowspan=cell.rowspan,+ )+ for cell in row.children+ if not cell.vmerge+ ]++ return _success(rows)+++ def remove_unmerged_table_cells(rows):+ return list(map(+ transforms.element_of_type(+ documents.TableCellUnmerged,+ lambda cell: documents.table_cell(+ children=cell.children,+ colspan=cell.colspan,+ rowspan=cell.rowspan,+ ),+ ),+ rows,+ ))+++ def read_child_elements(element):+ return _read_xml_elements(element.children)+++ def pict(element):+ return read_child_elements(element).to_extra()+++ def hyperlink(element):+ relationship_id = element.attributes.get("r:id")+ anchor = element.attributes.get("w:anchor")+ target_frame = element.attributes.get("w:tgtFrame") or None+ children_result = _read_xml_elements(element.children)++ def create(**kwargs):+ return children_result.map(lambda children: documents.hyperlink(+ children=children,+ target_frame=target_frame,+ **kwargs+ ))++ if relationship_id is not None:+ href = relationships.find_target_by_relationship_id(relationship_id)+ if anchor is not None:+ href = replace_fragment(href, anchor)++ return create(href=href)+ elif anchor is not None:+ return create(anchor=anchor)+ else:+ return children_result+++ def bookmark_start(element):+ name = element.attributes.get("w:name")+ if name == "_GoBack":+ return _empty_result+ else:+ return _success(documents.bookmark(name))+++ def break_(element):+ break_type = element.attributes.get("w:type")++ if not break_type or break_type == "textWrapping":+ return _success(documents.line_break)+ elif break_type == "page":+ return _success(documents.page_break)+ elif break_type == "column":+ return _success(documents.column_break)+ else:+ warning = results.warning("Unsupported break type: {0}".format(break_type))+ return _empty_result_with_message(warning)+++ def inline(element):+ properties_element = element.find_child_or_null("wp:docPr")++ properties = properties_element.attributes+ if properties.get("descr", "").strip():+ alt_text = properties.get("descr")+ else:+ alt_text = properties.get("title")++ hlink_click_element = properties_element.find_child_or_null("a:hlinkClick")+ hyperlink_relationship_id = hlink_click_element.attributes.get("r:id")+ if hyperlink_relationship_id:+ href = relationships.find_target_by_relationship_id(hyperlink_relationship_id)+ else:+ href = None++ blips = element.find_children("a:graphic") \+ .find_children("a:graphicData") \+ .find_children("pic:pic") \+ .find_children("pic:blipFill") \+ .find_children("a:blip")+ return _read_blips(blips, alt_text=alt_text, href=href)++ def _read_blips(blips, alt_text, href):+ return _ReadResult.concat(lists.map(lambda blip: _read_blip(blip, alt_text=alt_text, href=href), blips))++ def _read_blip(element, alt_text, href):+ blip_image = _find_blip_image(element)++ if blip_image is None:+ warning = results.warning("Could not find image file for a:blip element")+ return _empty_result_with_message(warning)++ result = _read_image(blip_image, alt_text)+ if href is None:+ return result+ else:+ return result.map(lambda image_elements: documents.hyperlink(+ image_elements,+ href=href,+ ))++ def _read_image(image_file, alt_text):+ image_path, open_image = image_file+ content_type = content_types.find_content_type(image_path)+ image = documents.image(alt_text=alt_text, content_type=content_type, open=open_image)++ if content_type in ["image/png", "image/gif", "image/jpeg", "image/svg+xml", "image/tiff"]:+ messages = []+ else:+ messages = [results.warning("Image of type {0} is unlikely to display in web browsers".format(content_type))]++ return _element_result_with_messages(image, messages)++ def _find_blip_image(element):+ embed_relationship_id = element.attributes.get("r:embed")+ link_relationship_id = element.attributes.get("r:link")+ if embed_relationship_id is not None:+ return _find_embedded_image(embed_relationship_id)+ elif link_relationship_id is not None:+ return _find_linked_image(link_relationship_id)+ else:+ return None++ def _find_embedded_image(relationship_id):+ target = relationships.find_target_by_relationship_id(relationship_id)+ image_path = uri_to_zip_entry_name("word", target)++ def open_image():+ image_file = docx_file.open(image_path)+ if hasattr(image_file, "__exit__"):+ return image_file+ else:+ return contextlib.closing(image_file)++ return image_path, open_image+++ def _find_linked_image(relationship_id):+ image_path = relationships.find_target_by_relationship_id(relationship_id)++ def open_image():+ return files.open(image_path)++ return image_path, open_image++ def read_imagedata(element):+ relationship_id = element.attributes.get("r:id")+ if relationship_id is None:+ warning = results.warning("A v:imagedata element without a relationship ID was ignored")+ return _empty_result_with_message(warning)+ else:+ title = element.attributes.get("o:title")+ return _read_image(_find_embedded_image(relationship_id), title)++ def note_reference_reader(note_type):+ def note_reference(element):+ return _success(documents.note_reference(note_type, element.attributes["w:id"]))++ return note_reference++ def read_comment_reference(element):+ return _success(documents.comment_reference(element.attributes["w:id"]))++ def alternate_content(element):+ return read_child_elements(element.find_child_or_null("mc:Fallback"))++ def read_sdt(element):+ content_result = read_child_elements(element.find_child_or_null("w:sdtContent"))++ def handle_content(content):+ # From the WordML standard: https://learn.microsoft.com/en-us/openspecs/office_standards/ms-docx/3350cb64-931f-41f7-8824-f18b2568ce66+ #+ # > A CT_SdtCheckbox element that specifies that the parent+ # > structured document tag is a checkbox when displayed in the+ # > document. The parent structured document tag contents MUST+ # > contain a single character and optionally an additional+ # > character in a deleted run.+ checkbox = element.find_child_or_null("w:sdtPr").find_child("wordml:checkbox")++ if checkbox is None:+ return content++ checked_element = checkbox.find_child("wordml:checked")+ is_checked = (+ checked_element is not None and+ read_boolean_attribute_value(checked_element.attributes.get("wordml:val"))+ )+ document_checkbox = documents.checkbox(checked=is_checked)++ has_checkbox = False++ def transform_text(text):+ nonlocal has_checkbox+ if len(text.value) > 0 and not has_checkbox:+ has_checkbox = True+ return document_checkbox+ else:+ return text++ replaced_content = list(map(+ transforms.element_of_type(documents.Text, transform_text),+ content,+ ))++ if has_checkbox:+ return replaced_content+ else:+ return document_checkbox++ return content_result.map(handle_content)++ handlers = {+ "w:t": text,+ "w:r": run,+ "w:p": paragraph,+ "w:fldChar": read_fld_char,+ "w:instrText": read_instr_text,+ "w:tab": tab,+ "w:noBreakHyphen": no_break_hyphen,+ "w:softHyphen": soft_hyphen,+ "w:sym": symbol,+ "w:tbl": table,+ "w:tr": table_row,+ "w:tc": table_cell,+ "w:ins": read_child_elements,+ "w:object": read_child_elements,+ "w:smartTag": read_child_elements,+ "w:drawing": read_child_elements,+ "v:group": read_child_elements,+ "v:rect": read_child_elements,+ "v:roundrect": read_child_elements,+ "v:shape": read_child_elements,+ "v:textbox": read_child_elements,+ "w:txbxContent": read_child_elements,+ "w:pict": pict,+ "w:hyperlink": hyperlink,+ "w:bookmarkStart": bookmark_start,+ "w:br": break_,+ "wp:inline": inline,+ "wp:anchor": inline,+ "v:imagedata": read_imagedata,+ "w:footnoteReference": note_reference_reader("footnote"),+ "w:endnoteReference": note_reference_reader("endnote"),+ "w:commentReference": read_comment_reference,+ "mc:AlternateContent": alternate_content,+ "w:sdt": read_sdt+ }++ def read(element):+ handler = handlers.get(element.name)+ if handler is None:+ if element.name not in _ignored_elements:+ warning = results.warning("An unrecognised element was ignored: {0}".format(element.name))+ return _empty_result_with_message(warning)+ else:+ return _empty_result+ else:+ return handler(element)+++ def _read_xml_elements(nodes):+ elements = filter(lambda node: isinstance(node, XmlElement), nodes)+ return _ReadResult.concat(lists.map(read, elements))++ return _read_xml_elements+++def _inner_text(node):+ if node.node_type == node_types.text:+ return node.value+ else:+ return "".join(_inner_text(child) for child in node.children)++++class _ReadResult(object):+ @staticmethod+ def concat(results):+ return _ReadResult(+ lists.flat_map(lambda result: result.elements, results),+ lists.flat_map(lambda result: result.extra, results),+ lists.flat_map(lambda result: result.messages, results))+++ @staticmethod+ def map_results(first, second, func):+ return _ReadResult(+ [func(first.elements, second.elements)],+ first.extra + second.extra,+ first.messages + second.messages)++ def __init__(self, elements, extra, messages):+ self.elements = elements+ self.extra = extra+ self.messages = messages++ def map(self, func):+ elements = func(self.elements)+ if not isinstance(elements, list):+ elements = [elements]+ return _ReadResult(+ elements,+ self.extra,+ self.messages)++ def flat_map(self, func):+ result = func(self.elements)+ return _ReadResult(+ result.elements,+ self.extra + result.extra,+ self.messages + result.messages)+++ def to_extra(self):+ return _ReadResult([], _concat(self.extra, self.elements), self.messages)++ def append_extra(self):+ return _ReadResult(_concat(self.elements, self.extra), [], self.messages)++def _success(elements):+ if not isinstance(elements, list):+ elements = [elements]+ return _ReadResult(elements, [], [])++def _element_result_with_messages(element, messages):+ return _elements_result_with_messages([element], messages)++def _elements_result_with_messages(elements, messages):+ return _ReadResult(elements, [], messages)++_empty_result = _ReadResult([], [], [])++def _empty_result_with_message(message):+ return _ReadResult([], [], [message])++def _concat(*values):+ result = []+ for value in values:+ for element in value:+ result.append(element)+ return result+++def _is_int(value):+ if value is None:+ return False++ try:+ int(value)+ except ValueError:+ return False++ return Truediff --git a/mineru/model/utils/docx/mammoth/conversion.py b/mineru/model/utils/docx/mammoth/conversion.pynew file mode 100644index 00000000..eb73945c--- /dev/null+++ b/mineru/model/utils/docx/mammoth/conversion.py@@ -0,0 +1,384 @@+# coding=utf-8++from __future__ import unicode_literals++from functools import partial++import cobble++from . import documents, results, html_paths, html+from . import writers+from .lists import find_index+++def convert_document_element_to_html(element,+ style_map=None,+ convert_image=None,+ id_prefix=None,+ output_format=None,+ ignore_empty_paragraphs=True):+ if style_map is None:+ style_map = []++ if id_prefix is None:+ id_prefix = ""++ if isinstance(element, documents.Document):+ comments = dict(+ (comment.comment_id, comment)+ for comment in element.comments+ )+ else:+ comments = {}++ messages = []+ converter = _DocumentConverter(+ messages=messages,+ style_map=style_map,+ convert_image=convert_image,+ id_prefix=id_prefix,+ ignore_empty_paragraphs=ignore_empty_paragraphs,+ note_references=[],+ comments=comments,+ )+ context = _ConversionContext(is_table_header=False)+ nodes = converter.visit(element, context)++ writer = writers.writer(output_format)+ html.write(writer, html.collapse(html.strip_empty(nodes)))+ return results.Result(writer.as_string(), messages)+++class _ConversionContext(object):+ is_table_header = cobble.field()++ def copy(self, **kwargs):+ return cobble.copy(self, **kwargs)+++class _DocumentConverter(documents.element_visitor(args=1)):+ def __init__(self, messages, style_map, convert_image, id_prefix, ignore_empty_paragraphs, note_references,+ comments):+ self._messages = messages+ self._style_map = style_map+ self._id_prefix = id_prefix+ self._ignore_empty_paragraphs = ignore_empty_paragraphs+ self._note_references = note_references+ self._referenced_comments = []+ self._convert_image = convert_image+ self._comments = comments++ def visit_document(self, document, context):+ nodes = self._visit_all(document.children, context)+ notes = [+ document.notes.resolve(reference)+ for reference in self._note_references+ ]+ notes_list = html.element("ol", {}, self._visit_all(notes, context))+ comments = html.element("dl", {}, [+ html_node+ for referenced_comment in self._referenced_comments+ for html_node in self.visit_comment(referenced_comment, context)+ ])+ return nodes + [notes_list, comments]++ def visit_paragraph(self, paragraph, context):+ def children():+ content = self._visit_all(paragraph.children, context)+ if self._ignore_empty_paragraphs:+ return content+ else:+ return [html.force_write] + content++ html_path = self._find_html_path_for_paragraph(paragraph)+ return html_path.wrap(children)++ def visit_run(self, run, context):+ nodes = lambda: self._visit_all(run.children, context)+ paths = []+ if run.highlight is not None:+ style = self._find_style(Highlight(color=run.highlight), "highlight")+ if style is not None:+ paths.append(style.html_path)+ if run.is_small_caps:+ paths.append(self._find_style_for_run_property("small_caps"))+ if run.is_all_caps:+ paths.append(self._find_style_for_run_property("all_caps"))+ if run.is_strikethrough:+ paths.append(self._find_style_for_run_property("strikethrough", default="s"))+ if run.is_underline:+ paths.append(self._find_style_for_run_property("underline"))+ if run.vertical_alignment == documents.VerticalAlignment.subscript:+ paths.append(html_paths.element(["sub"], fresh=False))+ if run.vertical_alignment == documents.VerticalAlignment.superscript:+ paths.append(html_paths.element(["sup"], fresh=False))+ if run.is_italic:+ paths.append(self._find_style_for_run_property("italic", default="em"))+ if run.is_bold:+ paths.append(self._find_style_for_run_property("bold", default="strong"))+ paths.append(self._find_html_path_for_run(run))++ for path in paths:+ nodes = partial(path.wrap, nodes)++ return nodes()++ def _find_style_for_run_property(self, element_type, default=None):+ style = self._find_style(None, element_type)+ if style is not None:+ return style.html_path+ elif default is not None:+ return html_paths.element(default, fresh=False)+ else:+ return html_paths.empty++ def visit_image(self, image, context):+ return []++ def visit_text(self, text, context):+ return [html.text(text.value)]++ def visit_hyperlink(self, hyperlink, context):+ if hyperlink.anchor is None:+ href = hyperlink.href+ else:+ href = "#{0}".format(self._html_id(hyperlink.anchor))++ attributes = {"href": href}+ if hyperlink.target_frame is not None:+ attributes["target"] = hyperlink.target_frame++ nodes = self._visit_all(hyperlink.children, context)+ return [html.collapsible_element("a", attributes, nodes)]++ def visit_checkbox(self, checkbox, context):+ attributes = {"type": "checkbox"}++ if checkbox.checked:+ attributes["checked"] = "checked"++ return [html.element("input", attributes)]++ def visit_bookmark(self, bookmark, context):+ element = html.collapsible_element(+ "a",+ {"id": self._html_id(bookmark.name)},+ [html.force_write])+ return [element]++ def visit_tab(self, tab, context):+ return [html.text("\t")]++ _default_table_path = html_paths.path([html_paths.element(["table"], fresh=True)])++ def visit_table(self, table, context):+ return self._find_html_path(table, "table", self._default_table_path) \+ .wrap(lambda: self._convert_table_children(table, context))++ def _convert_table_children(self, table, context):+ body_index = find_index(+ lambda child: not isinstance(child, documents.TableRow) or not child.is_header,+ table.children,+ )+ if body_index is None:+ body_index = len(table.children)++ if body_index == 0:+ children = self._visit_all(table.children, context.copy(is_table_header=False))+ else:+ head_rows = self._visit_all(table.children[:body_index], context.copy(is_table_header=True))+ body_rows = self._visit_all(table.children[body_index:], context.copy(is_table_header=False))+ children = [+ html.element("thead", {}, head_rows),+ html.element("tbody", {}, body_rows),+ ]++ return [html.force_write] + children++ def visit_table_row(self, table_row, context):+ return [html.element("tr", {}, [html.force_write] + self._visit_all(table_row.children, context))]++ def visit_table_cell(self, table_cell, context):+ if context.is_table_header:+ tag_name = "th"+ else:+ tag_name = "td"+ attributes = {}+ if table_cell.colspan != 1:+ attributes["colspan"] = str(table_cell.colspan)+ if table_cell.rowspan != 1:+ attributes["rowspan"] = str(table_cell.rowspan)+ nodes = [html.force_write] + self._visit_all(table_cell.children, context)+ return [+ html.element(tag_name, attributes, nodes)+ ]++ def visit_break(self, break_, context):+ return self._find_html_path_for_break(break_).wrap(lambda: [])++ def _find_html_path_for_break(self, break_):+ style = self._find_style(break_, "break")+ if style is not None:+ return style.html_path+ elif break_.break_type == "line":+ return html_paths.path([html_paths.element("br", fresh=True)])+ else:+ return html_paths.empty++ def visit_note_reference(self, note_reference, context):+ self._note_references.append(note_reference)+ note_number = len(self._note_references)+ return [+ html.element("sup", {}, [+ html.element("a", {+ "href": "#" + self._note_html_id(note_reference),+ "id": self._note_ref_html_id(note_reference),+ }, [html.text("[{0}]".format(note_number))])+ ])+ ]++ def visit_note(self, note, context):+ note_body = self._visit_all(note.body, context) + [+ html.collapsible_element("p", {}, [+ html.text(" "),+ html.element("a", {"href": "#" + self._note_ref_html_id(note)}, [+ html.text(_up_arrow)+ ]),+ ])+ ]+ return [+ html.element("li", {"id": self._note_html_id(note)}, note_body)+ ]++ def visit_comment_reference(self, reference, context):+ def nodes():+ comment = self._comments[reference.comment_id]+ count = len(self._referenced_comments) + 1+ label = "[{0}{1}]".format(_comment_author_label(comment), count)+ self._referenced_comments.append((label, comment))+ return [+ # TODO: remove duplication with note references+ html.element("a", {+ "href": "#" + self._referent_html_id("comment", reference.comment_id),+ "id": self._reference_html_id("comment", reference.comment_id),+ }, [html.text(label)])+ ]++ html_path = self._find_html_path(+ None,+ "comment_reference",+ default=html_paths.ignore,+ )++ return html_path.wrap(nodes)++ def visit_comment(self, referenced_comment, context):+ label, comment = referenced_comment+ # TODO remove duplication with notes+ body = self._visit_all(comment.body, context) + [+ html.collapsible_element("p", {}, [+ html.text(" "),+ html.element("a", {"href": "#" + self._reference_html_id("comment", comment.comment_id)}, [+ html.text(_up_arrow)+ ]),+ ])+ ]+ return [+ html.element(+ "dt",+ {"id": self._referent_html_id("comment", comment.comment_id)},+ [html.text("Comment {0}".format(label))],+ ),+ html.element("dd", {}, body),+ ]++ def _visit_all(self, elements, context):+ return [+ html_node+ for element in elements+ for html_node in self.visit(element, context)+ ]++ def _find_html_path_for_paragraph(self, paragraph):+ default = html_paths.path([html_paths.element("p", fresh=True)])+ return self._find_html_path(paragraph, "paragraph", default, warn_unrecognised=True)++ def _find_html_path_for_run(self, run):+ return self._find_html_path(run, "run", default=html_paths.empty, warn_unrecognised=True)++ def _find_html_path(self, element, element_type, default, warn_unrecognised=False):+ style = self._find_style(element, element_type)+ if style is not None:+ return style.html_path++ if warn_unrecognised and getattr(element, "style_id", None) is not None:+ self._messages.append(results.warning(+ "Unrecognised {0} style: {1} (Style ID: {2})".format(+ element_type, element.style_name, element.style_id)+ ))++ return default++ def _find_style(self, element, element_type):+ for style in self._style_map:+ document_matcher = style.document_matcher+ if _document_matcher_matches(document_matcher, element, element_type):+ return style++ def _note_html_id(self, note):+ return self._referent_html_id(note.note_type, note.note_id)++ def _note_ref_html_id(self, note):+ return self._reference_html_id(note.note_type, note.note_id)++ def _referent_html_id(self, reference_type, reference_id):+ return self._html_id("{0}-{1}".format(reference_type, reference_id))++ def _reference_html_id(self, reference_type, reference_id):+ return self._html_id("{0}-ref-{1}".format(reference_type, reference_id))++ def _html_id(self, suffix):+ return "{0}{1}".format(self._id_prefix, suffix)+++class Highlight:+ color = cobble.field()+++def _document_matcher_matches(matcher, element, element_type):+ if matcher.element_type in ["underline", "strikethrough", "all_caps", "small_caps", "bold", "italic",+ "comment_reference"]:+ return matcher.element_type == element_type+ elif matcher.element_type == "highlight":+ return (+ matcher.element_type == element_type and+ (matcher.color is None or matcher.color == element.color)+ )+ elif matcher.element_type == "break":+ return (+ matcher.element_type == element_type and+ matcher.break_type == element.break_type+ )+ else: # matcher.element_type in ["paragraph", "run"]:+ return (+ matcher.element_type == element_type and (+ matcher.style_id is None or+ matcher.style_id == element.style_id+ ) and (+ matcher.style_name is None or+ element.style_name is not None and (matcher.style_name.matches(element.style_name))+ ) and (+ element_type != "paragraph" or+ matcher.numbering is None or+ matcher.numbering == element.numbering+ )+ )+++def _comment_author_label(comment):+ return comment.author_initials or ""+++_up_arrow = "↑"diff --git a/mineru/model/utils/docx/mammoth/office_xml.py b/mineru/model/utils/docx/mammoth/office_xml.pynew file mode 100644index 00000000..ac8a6e20--- /dev/null+++ b/mineru/model/utils/docx/mammoth/office_xml.py@@ -0,0 +1,48 @@+from .lists import flat_map+from .xmlparser import parse_xml, XmlElement, parse_xml_str++_namespaces = [+ # Transitional format+ ("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"),+ ("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),+ ("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"),+ ("a", "http://schemas.openxmlformats.org/drawingml/2006/main"),+ ("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"),++ # Strict format+ ("w", "http://purl.oclc.org/ooxml/wordprocessingml/main"),+ ("r", "http://purl.oclc.org/ooxml/officeDocument/relationships"),+ ("wp", "http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing"),+ ("a", "http://purl.oclc.org/ooxml/drawingml/main"),+ ("pic", "http://purl.oclc.org/ooxml/drawingml/picture"),++ # Common+ ("content-types", "http://schemas.openxmlformats.org/package/2006/content-types"),+ ("relationships", "http://schemas.openxmlformats.org/package/2006/relationships"),+ ("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"),+ ("v", "urn:schemas-microsoft-com:vml"),+ ("office-word", "urn:schemas-microsoft-com:office:word"),++ # [MS-DOCX]: Word Extensions to the Office Open XML (.docx) File Format+ # https://learn.microsoft.com/en-us/openspecs/office_standards/ms-docx/b839fe1f-e1ca-4fa6-8c26-5954d0abbccd+ ("wordml", "http://schemas.microsoft.com/office/word/2010/wordml"),+]+++def read(fileobj):+ i = parse_xml(fileobj, _namespaces)+ return _collapse_alternate_content(i)[0]++def read_str(xml_str):+ i = parse_xml_str(xml_str, _namespaces)+ return _collapse_alternate_content(i)[0]++def _collapse_alternate_content(node):+ if isinstance(node, XmlElement):+ if node.name == "mc:AlternateContent":+ return node.find_child_or_null("mc:Fallback").children+ else:+ node.children = flat_map(_collapse_alternate_content, node.children)+ return [node]+ else:+ return [node]