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 Excel to HTML conversion by extracting non-empty rows and rendering compact tables
myhloli7680a7172a13
diff --git a/README.md b/README.mdindex a49dcfa4..0423b732 100644--- a/README.md+++ b/README.md@@ -326,7 +326,6 @@ This repository is licensed under the [MinerU Open Source License](https://githu- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)- [pdftext](https://github.com/datalab-to/pdftext)-- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)- [pypdf](https://github.com/py-pdf/pypdf)- [magika](https://github.com/google/magika)- [vLLM](https://github.com/vllm-project/vllm)diff --git a/README_zh-CN.md b/README_zh-CN.mdindex 075d1cb8..d6e33077 100644--- a/README_zh-CN.md+++ b/README_zh-CN.md@@ -333,7 +333,6 @@ mineru -p <input_path> -o <output_path> -b pipeline- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)- [pdftext](https://github.com/datalab-to/pdftext)-- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)- [pypdf](https://github.com/py-pdf/pypdf)- [magika](https://github.com/google/magika)- [vLLM](https://github.com/vllm-project/vllm)diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.pyindex 7aa5c455..23dc48ae 100644--- a/mineru/utils/pdf_classify.py+++ b/mineru/utils/pdf_classify.py@@ -1,37 +1,23 @@# Copyright (c) Opendatalab. All rights reserved.-import osimport refrom io import BytesIO-import numpy as npimport pypdfium2 as pdfiumimport pypdfium2.raw as pdfium_cfrom loguru import loggerfrom pypdf import PdfReader-from pdfminer.converter import PDFPageAggregator-from pdfminer.high_level import extract_text-from pdfminer.layout import LAParams, LTFigure, LTImage-from pdfminer.pdfdocument import PDFDocument-from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager-from pdfminer.pdfpage import PDFPage-from pdfminer.pdfparser import PDFParserfrom mineru.utils.pdfium_guard import (close_pdfium_document,open_pdfium_document,pdfium_guard,)-PDF_CLASSIFY_STRATEGY_ENV = "MINERU_PDF_CLASSIFY_STRATEGY"-PDF_CLASSIFY_STRATEGY_HYBRID = "hybrid"-PDF_CLASSIFY_STRATEGY_LEGACY = "legacy"-MAX_SAMPLE_PAGES = 10CHARS_THRESHOLD = 50HIGH_IMAGE_COVERAGE_THRESHOLD = 0.8-CID_RATIO_THRESHOLD = 0.05TEXT_QUALITY_MIN_CHARS = 300TEXT_QUALITY_BAD_THRESHOLD = 0.03-TEXT_QUALITY_GOOD_THRESHOLD = 0.005+UNICODE_MAP_ERROR_RATIO_THRESHOLD = 0.04MAX_PAGE_ASPECT_RATIO = 10.0SUSPICIOUS_CJK_72XX_START = 0x7280SUSPICIOUS_CJK_72XX_END = 0x72DF@@ -69,39 +55,17 @@ def classify(pdf_bytes):"txt" if the PDF can be parsed as text, otherwise "ocr"."""- strategy = get_pdf_classify_strategy()- if strategy == PDF_CLASSIFY_STRATEGY_LEGACY:- return classify_legacy(pdf_bytes)return classify_hybrid(pdf_bytes)-def get_pdf_classify_strategy() -> str:- strategy = os.getenv(- PDF_CLASSIFY_STRATEGY_ENV, PDF_CLASSIFY_STRATEGY_HYBRID- ).strip().lower()- if strategy not in {- PDF_CLASSIFY_STRATEGY_HYBRID,- PDF_CLASSIFY_STRATEGY_LEGACY,- }:- logger.warning(- f"Invalid {PDF_CLASSIFY_STRATEGY_ENV} value: {strategy}, "- f"fall back to {PDF_CLASSIFY_STRATEGY_HYBRID}"- )- return PDF_CLASSIFY_STRATEGY_HYBRID- return strategy--def classify_hybrid(pdf_bytes):"""Fast PDF classification path.- The hybrid path uses pdfium + pypdf as the main path and falls back to- pdfminer only for gray-zone samples.+ The hybrid path uses pdfium + pypdf to detect text PDFs and garbled PDFs."""pdf = None- page_indices = []- should_run_pdfminer_fallback = Falsetry:with pdfium_guard():@@ -132,6 +96,21 @@ def classify_hybrid(pdf_bytes):if avg_cleaned_chars_per_page < CHARS_THRESHOLD:return "ocr"+ unicode_map_error_signal = _get_unicode_map_error_signal_from_samples(+ text_samples+ )+ if (+ unicode_map_error_signal["unicode_map_error_ratio"]+ >= UNICODE_MAP_ERROR_RATIO_THRESHOLD+ ):+ logger.debug(+ "Classify PDF as OCR due to PDFium Unicode map errors: "+ f"errors={unicode_map_error_signal['unicode_map_error_count']}, "+ f"total={unicode_map_error_signal['total_chars']}, "+ f"ratio={unicode_map_error_signal['unicode_map_error_ratio']:.4f}"+ )+ return "ocr"+if detect_cid_font_signal_pypdf(pdf_bytes, page_indices):return "ocr"@@ -139,12 +118,11 @@ def classify_hybrid(pdf_bytes):total_chars = text_quality_signal["total_chars"]abnormal_ratio = text_quality_signal["abnormal_ratio"]- if total_chars >= TEXT_QUALITY_MIN_CHARS:- if abnormal_ratio >= TEXT_QUALITY_BAD_THRESHOLD:- return "ocr"- should_run_pdfminer_fallback = abnormal_ratio > TEXT_QUALITY_GOOD_THRESHOLD- else:- should_run_pdfminer_fallback = True+ if (+ total_chars >= TEXT_QUALITY_MIN_CHARS+ and abnormal_ratio >= TEXT_QUALITY_BAD_THRESHOLD+ ):+ return "ocr"u72xx_signal = _get_u72xx_text_signal_from_samples(text_samples)if (@@ -187,55 +165,9 @@ def classify_hybrid(pdf_bytes):finally:close_pdfium_document(pdf)- if should_run_pdfminer_fallback:- sample_pdf_bytes = extract_selected_pages(pdf_bytes, page_indices)- if not sample_pdf_bytes:- return "ocr"- if detect_invalid_chars_pdfminer_fallback(sample_pdf_bytes):- return "ocr"-return "txt"-def classify_legacy(pdf_bytes):- """- Legacy classification path kept for rollback and A/B comparison.- """-- sample_pdf_bytes = extract_pages(pdf_bytes)- if not sample_pdf_bytes:- return "ocr"- pdf = None- try:- with pdfium_guard():- pdf = open_pdfium_document(pdfium.PdfDocument, sample_pdf_bytes)- page_count = len(pdf)- if page_count == 0:- return "ocr"-- pages_to_check = min(page_count, MAX_SAMPLE_PAGES)-- if (- get_avg_cleaned_chars_per_page(pdf, pages_to_check) < CHARS_THRESHOLD- ) or detect_invalid_chars(sample_pdf_bytes):- return "ocr"-- if (- get_high_image_coverage_ratio(sample_pdf_bytes, pages_to_check)- >= HIGH_IMAGE_COVERAGE_THRESHOLD- ):- return "ocr"-- return "txt"-- except Exception as e:- logger.warning(f"Failed to classify PDF with legacy strategy: {e}")- return "ocr"-- finally:- close_pdfium_document(pdf)--def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES):if page_count <= 0 or max_pages <= 0:return []@@ -285,22 +217,6 @@ def get_extreme_aspect_ratio_page_pdfium(return None, None-def get_avg_cleaned_chars_per_page(pdf_doc, pages_to_check):- total_chars = 0- cleaned_total_chars = 0-- for i in range(pages_to_check):- page = pdf_doc[i]- text_page = page.get_textpage()- text = text_page.get_text_bounded()- total_chars += len(text)- cleaned_text = re.sub(r"\s+", "", text)- cleaned_total_chars += len(cleaned_text)-- avg_cleaned_chars_per_page = cleaned_total_chars / pages_to_check- return avg_cleaned_chars_per_page--def _collect_pdfium_text_samples(pdf_doc, page_indices):"""一次性收集抽样页的 textpage 和文本,避免分类链路重复读取 PDFium 文本。"""text_samples = []@@ -388,6 +304,31 @@ def get_text_quality_signal_pdfium(pdf_doc, page_indices):return _get_text_quality_signal_from_samples(text_samples)+def _get_unicode_map_error_signal_from_samples(text_samples):+ """统计 PDFium 字符级 Unicode 映射失败比例,用于识别无法可靠抽取的乱码文本。"""+ total_chars = 0+ unicode_map_error_count = 0++ for text_sample in text_samples:+ text_page = text_sample["text_page"]+ char_count = text_page.count_chars()+ total_chars += char_count++ for char_index in range(char_count):+ if pdfium_c.FPDFText_HasUnicodeMapError(text_page, char_index):+ unicode_map_error_count += 1++ unicode_map_error_ratio = 0.0+ if total_chars > 0:+ unicode_map_error_ratio = unicode_map_error_count / total_chars++ return {+ "total_chars": total_chars,+ "unicode_map_error_count": unicode_map_error_count,+ "unicode_map_error_ratio": unicode_map_error_ratio,+ }++def _get_u72xx_text_signal_from_samples(text_samples):"""基于已缓存的抽样页文本统计扣除常用字后的 U+7280-U+72DF 字符占比。"""cjk_chars = 0@@ -542,62 +483,6 @@ def _resolve_pdf_object(obj):return obj-def get_high_image_coverage_ratio(sample_pdf_bytes, pages_to_check):- pdf_stream = BytesIO(sample_pdf_bytes)- parser = PDFParser(pdf_stream)- document = PDFDocument(parser)-- if not document.is_extractable:- return 1.0-- rsrcmgr = PDFResourceManager()- laparams = LAParams(- line_overlap=0.5,- char_margin=2.0,- line_margin=0.5,- word_margin=0.1,- boxes_flow=None,- detect_vertical=False,- all_texts=False,- )- device = PDFPageAggregator(rsrcmgr, laparams=laparams)- interpreter = PDFPageInterpreter(rsrcmgr, device)-- high_image_coverage_pages = 0- page_count = 0-- for page in PDFPage.create_pages(document):- if page_count >= pages_to_check:- break-- interpreter.process_page(page)- layout = device.get_result()-- page_width = layout.width- page_height = layout.height- page_area = page_width * page_height-- image_area = 0- for element in layout:- if isinstance(element, (LTImage, LTFigure)):- img_width = element.width- img_height = element.height- image_area += img_width * img_height-- coverage_ratio = min(image_area / page_area, 1.0) if page_area > 0 else 0- if coverage_ratio >= HIGH_IMAGE_COVERAGE_THRESHOLD:- high_image_coverage_pages += 1-- page_count += 1-- pdf_stream.close()-- if page_count == 0:- return 0.0-- return high_image_coverage_pages / page_count--def get_high_image_coverage_ratio_pdfium(pdf_doc, page_indices):high_image_coverage_pages = 0@@ -624,122 +509,6 @@ def get_high_image_coverage_ratio_pdfium(pdf_doc, page_indices):return high_image_coverage_pages / len(page_indices)-def extract_pages(src_pdf_bytes: bytes) -> bytes:- """- Extract up to 10 random pages and return them as a new PDF.- """-- pdf = None- sample_docs = None- try:- with pdfium_guard():- pdf = open_pdfium_document(pdfium.PdfDocument, src_pdf_bytes)- total_page = len(pdf)- if total_page == 0:- logger.warning("PDF is empty, return empty document")- return b""-- if total_page <= MAX_SAMPLE_PAGES:- return src_pdf_bytes-- select_page_cnt = min(MAX_SAMPLE_PAGES, total_page)- page_indices = np.random.choice(- total_page, select_page_cnt, replace=False- ).tolist()-- sample_docs = open_pdfium_document(pdfium.PdfDocument.new)- sample_docs.import_pages(pdf, page_indices)-- output_buffer = BytesIO()- sample_docs.save(output_buffer)- return output_buffer.getvalue()- except Exception as e:- logger.exception(e)- return src_pdf_bytes- finally:- close_pdfium_document(pdf)- close_pdfium_document(sample_docs)---def extract_selected_pages(src_pdf_bytes: bytes, page_indices) -> bytes:- """- Extract specific pages and return them as a new PDF.- """-- selected_page_indices = sorted(set(page_indices))- if not selected_page_indices:- return b""-- pdf = None- sample_docs = None- try:- with pdfium_guard():- pdf = open_pdfium_document(pdfium.PdfDocument, src_pdf_bytes)- total_page = len(pdf)- if total_page == 0:- logger.warning("PDF is empty, return empty document")- return b""-- selected_page_indices = [- page_index- for page_index in selected_page_indices- if 0 <= page_index < total_page- ]- if not selected_page_indices:- return b""-- if selected_page_indices == list(range(total_page)):- return src_pdf_bytes-- sample_docs = open_pdfium_document(pdfium.PdfDocument.new)- sample_docs.import_pages(pdf, selected_page_indices)-- output_buffer = BytesIO()- sample_docs.save(output_buffer)- return output_buffer.getvalue()- except Exception as e:- logger.exception(e)- return src_pdf_bytes- finally:- close_pdfium_document(pdf)- close_pdfium_document(sample_docs)---def detect_invalid_chars(sample_pdf_bytes: bytes) -> bool:- """- Detect whether a PDF contains invalid CID-style extracted text.- """-- sample_pdf_file_like_object = BytesIO(sample_pdf_bytes)- laparams = LAParams(- line_overlap=0.5,- char_margin=2.0,- line_margin=0.5,- word_margin=0.1,- boxes_flow=None,- detect_vertical=False,- all_texts=False,- )- text = extract_text(pdf_file=sample_pdf_file_like_object, laparams=laparams)- text = text.replace("\n", "")-- cid_pattern = re.compile(r"\(cid:\d+\)")- matches = cid_pattern.findall(text)- cid_count = len(matches)- cid_len = sum(len(match) for match in matches)- text_len = len(text)- if text_len == 0:- cid_chars_ratio = 0- else:- cid_chars_ratio = cid_count / (cid_count + text_len - cid_len)-- return cid_chars_ratio > CID_RATIO_THRESHOLD---def detect_invalid_chars_pdfminer_fallback(sample_pdf_bytes: bytes) -> bool:- return detect_invalid_chars(sample_pdf_bytes)--if __name__ == "__main__":with open("/Users/myhloli/pdf/luanma2x10.pdf", "rb") as f:p_bytes = f.read()diff --git a/pyproject.toml b/pyproject.tomlindex 17edca98..c15a3c6b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -35,7 +35,6 @@ dependencies = ["click>=8.1.7","loguru>=0.7.2","numpy>=1.21.6",- "pdfminer.six>=20251230","tqdm>=4.67.1","requests","httpx",