Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: implement DOCX processing in the converter

myhloli53fb1cd0554e
diff --git a/demo/demo.py b/demo/demo.py
index d729ad56..14c075c5 100644
--- a/demo/demo.py
+++ b/demo/demo.py
@@ -6,7 +6,7 @@ from pathlib import Path
from loguru import logger
-from mineru.cli.common import convert_pdf_bytes_to_bytes_by_pypdfium2, prepare_env, read_fn
+from mineru.cli.common import convert_pdf_bytes_to_bytes_by_pypdfium2, prepare_env, read_fn, _process_office_doc
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
@@ -42,6 +42,18 @@ def do_parse(
end_page_id=None, # End page ID for parsing, default is None (parse all pages until the end of the document)
):
+ need_remove_index = _process_office_doc(
+ output_dir,
+ pdf_bytes_list,
+ )
+ for index in sorted(need_remove_index, reverse=True):
+ del pdf_bytes_list[index]
+ del pdf_file_names[index]
+ del p_lang_list[index]
+ if not pdf_bytes_list:
+ logger.warning("No valid PDF or image files to process.")
+ return
+
if backend == "pipeline":
for idx, pdf_bytes in enumerate(pdf_bytes_list):
new_pdf_bytes = convert_pdf_bytes_to_bytes_by_pypdfium2(pdf_bytes, start_page_id, end_page_id)
@@ -254,14 +266,15 @@ def parse_doc(
if __name__ == '__main__':
# args
__dir__ = os.path.dirname(os.path.abspath(__file__))
- pdf_files_dir = os.path.join(__dir__, "pdfs")
+ pdf_files_dir = os.path.join(__dir__, "docx")
output_dir = os.path.join(__dir__, "output")
pdf_suffixes = ["pdf"]
+ docx_suffixes = ["docx"]
image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg"]
doc_path_list = []
for doc_path in Path(pdf_files_dir).glob('*'):
- if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes:
+ if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes + docx_suffixes:
doc_path_list.append(doc_path)
"""如果您由于网络问题无法下载模型,可以设置环境变量MINERU_MODEL_SOURCE为modelscope使用免代理仓库下载模型"""
diff --git a/mineru/cli/common.py b/mineru/cli/common.py
index 72c0a053..76f369a3 100644
--- a/mineru/cli/common.py
+++ b/mineru/cli/common.py
@@ -9,6 +9,7 @@ from loguru import logger
import pypdfium2 as pdfium
from mineru.data.data_reader_writer import FileBasedDataWriter
+from mineru.model.docx.main import convert_binary
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox, draw_line_sort_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.enum_class import MakeMode
@@ -413,6 +414,21 @@ async def _async_process_hybrid(
)
+def _process_office_doc(
+ output_dir,
+ pdf_bytes_list: list[bytes],
+):
+ need_remove_index = []
+ for i, file_bytes in enumerate(pdf_bytes_list):
+ file_suffix = guess_suffix_by_bytes(file_bytes)
+ if file_suffix in docx_suffixes:
+ need_remove_index.append(i)
+ # docx解析流程
+ result = convert_binary(io.BytesIO(file_bytes))
+ pass
+ return need_remove_index
+
+
def do_parse(
output_dir,
pdf_file_names: list[str],
@@ -435,6 +451,18 @@ def do_parse(
end_page_id=None,
**kwargs,
):
+ need_remove_index = _process_office_doc(
+ output_dir,
+ pdf_bytes_list,
+ )
+ for index in sorted(need_remove_index, reverse=True):
+ del pdf_bytes_list[index]
+ del pdf_file_names[index]
+ del p_lang_list[index]
+ if not pdf_bytes_list:
+ logger.warning("No valid PDF or image files to process.")
+ return
+
# 预处理PDF字节数据
pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
@@ -507,6 +535,18 @@ async def aio_do_parse(
end_page_id=None,
**kwargs,
):
+ need_remove_index = _process_office_doc(
+ output_dir,
+ pdf_bytes_list,
+ )
+ for index in sorted(need_remove_index, reverse=True):
+ del pdf_bytes_list[index]
+ del pdf_file_names[index]
+ del p_lang_list[index]
+ if not pdf_bytes_list:
+ logger.warning("No valid PDF or image files to process.")
+ return
+
# 预处理PDF字节数据
pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index 02d8ffdf..3c35472e 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -5,7 +5,7 @@ from pathlib import Path
from typing import BinaryIO, Optional, Union, Any, Final
import logging
-from PIL import Image, UnidentifiedImageError
+from PIL import Image
from loguru import logger
from docx import Document
from docx.oxml.xmlchemy import BaseOxmlElement
@@ -21,7 +21,7 @@ from mineru.model.utils.docx.mammoth.office_xml import read_str
from mineru.model.utils.docx.math.omml import oMath2Latex
from mineru.utils.docx_fomatting import Formatting, Script
from mineru.utils.enum_class import BlockType, ContentType
-from mineru.utils.hash_utils import bytes_md5
+from mineru.utils.pdf_reader import image_to_b64str
ACCEPTED_MIME_TYPE_PREFIXES = [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
@@ -58,7 +58,7 @@ class DocxConverter:
- a14: Office 2010 Drawing 命名空间
"""
- def __init__(self, file_path: str = None, output_path: str = None):
+ def __init__(self):
self.XML_KEY = (
"{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val"
)
@@ -72,8 +72,6 @@ class DocxConverter:
self.docx_obj = None
self.max_levels: int = 10 # 文档层次结构的最大层级数
self.parents: dict = {} # 父级节点映射
- self.file_path = file_path
- self.output_path = Path(output_path, Path(self.file_path).stem)
self.blocks = []
self.pre_num_id: int = -1 # 上一个处理元素的 numId
self.pre_ilevel: int = -1 # 上一个处理元素的缩进等级, 用于判断列表层级
@@ -82,33 +80,15 @@ class DocxConverter:
{}
) # 列表计数器 (numId, ilvl) -> count
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
- Path.mkdir(self.output_path, parents=True, exist_ok=True)
def convert(
self,
file_stream: BinaryIO,
- style_map: str = None,
):
self.docx_obj = Document(file_stream)
self._walk_linear(self.docx_obj.element.body)
- #
- # assert isinstance(webpage_text, str)
- #
- # # remove leading and trailing \n
- # webpage_text = webpage_text.strip()
-
- # return webpage_text
-
- # def convert_image(self, image):
- # with image.open() as image_bytes:
- # img_bytes = image_bytes.read()
- # img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)
- # img_numpy = cv2.imdecode(img_buffer_numpy, 1)
- # cv2.imwrite(
- # self.output_path.joinpath(image.alt_text + ".jpg").as_posix(), img_numpy
- # )
- # return {"src": self.output_path.joinpath(image.alt_text + ".jpg").as_posix()}
+
def _walk_linear(
self,
body: BaseOxmlElement,
@@ -486,15 +466,7 @@ class DocxConverter:
else:
image_bytes = BytesIO(image_data)
pil_image = Image.open(image_bytes)
- # p2 = doc.add_picture(
- # parent=self.parents[level - 1],
- # image=ImageRef.from_pil(image=pil_image, dpi=72),
- # caption=None,
- # content_layer=self.content_layer,
- # )
- md5 = bytes_md5(image_data)
- path = f"{self.output_path}/{md5}.jpg"
- pil_image.save(path)
+ img_base64 = image_to_b64str(pil_image)
image_block = {
"type": BlockType.IMAGE,
"bbox": [0, 0, 0, 0],
@@ -510,7 +482,7 @@ class DocxConverter:
"bbox": [0, 0, 0, 0],
"score": 1.0,
"type": ContentType.IMAGE,
- "image_path": path,
+ "image_base64": img_base64,
}
],
}
diff --git a/mineru/model/docx/main.py b/mineru/model/docx/main.py
index 69a4f4cf..fd20f6d4 100644
--- a/mineru/model/docx/main.py
+++ b/mineru/model/docx/main.py
@@ -1,16 +1,17 @@
from typing import BinaryIO
-from docx_converter import DocxConverter
+
+from mineru.model.docx.docx_converter import DocxConverter
def convert_path(file_path: str):
with open(file_path, "rb") as fh:
- return convert_binary(fh, file_path)
-
+ return convert_binary(fh)
-def convert_binary(file_binary: BinaryIO, file_path: str):
- converter = DocxConverter(file_path=file_path, output_path="./output")
- return converter.convert(file_binary)
+def convert_binary(file_binary: BinaryIO):
+ converter = DocxConverter()
+ converter.convert(file_binary)
+ return converter.blocks
if __name__ == "__main__":
- print(convert_path("testbak.docx"))
\ No newline at end of file
+ print(convert_path("test.docx"))
\ No newline at end of file