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: add aspect ratio checks and character count limits for PDF processing
myhloli0f43f17faecd
diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.pyindex f0fa8696..93bbf919 100644--- a/mineru/utils/pdf_classify.py+++ b/mineru/utils/pdf_classify.py@@ -32,6 +32,7 @@ CID_RATIO_THRESHOLD = 0.05TEXT_QUALITY_MIN_CHARS = 300TEXT_QUALITY_BAD_THRESHOLD = 0.03TEXT_QUALITY_GOOD_THRESHOLD = 0.005+MAX_PAGE_ASPECT_RATIO = 10.0_ALLOWED_CONTROL_CODES = {9, 10, 13}_PRIVATE_USE_AREA_START = 0xE000@@ -101,6 +102,17 @@ def classify_hybrid(pdf_bytes):if not page_indices:return "ocr"+ extreme_page_index, extreme_ratio = get_extreme_aspect_ratio_page_pdfium(+ pdf,+ page_indices,+ )+ if extreme_page_index is not None:+ logger.info(+ "Classify PDF as OCR due to extreme sampled-page aspect ratio: "+ f"page={extreme_page_index + 1}, ratio={extreme_ratio:.2f}"+ )+ return "ocr"+if (get_avg_cleaned_chars_per_page_pdfium(pdf, page_indices)< CHARS_THRESHOLD@@ -214,6 +226,24 @@ def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES):return sorted(indices)+def get_extreme_aspect_ratio_page_pdfium(+ pdf_doc,+ page_indices,+ max_page_aspect_ratio: float = MAX_PAGE_ASPECT_RATIO,+):+ for page_index in page_indices:+ page = pdf_doc[page_index]+ page_width, page_height = page.get_size()+ if page_width <= 0 or page_height <= 0:+ continue++ aspect_ratio = max(page_width / page_height, page_height / page_width)+ if aspect_ratio > max_page_aspect_ratio:+ return page_index, aspect_ratio++ return None, None++def get_avg_cleaned_chars_per_page(pdf_doc, pages_to_check):total_chars = 0cleaned_total_chars = 0diff --git a/mineru/utils/span_pre_proc.py b/mineru/utils/span_pre_proc.pyindex 4377110d..de74d52f 100644--- a/mineru/utils/span_pre_proc.py+++ b/mineru/utils/span_pre_proc.py@@ -13,6 +13,8 @@ from mineru.utils.enum_class import BlockType, ContentTypefrom mineru.utils.pdf_image_tools import get_crop_imgfrom mineru.utils.pdf_text_tool import get_page+MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535+def __replace_ligatures(text: str):ligatures = {@@ -29,6 +31,21 @@ def __replace_unicode(text: str):"""pdf_text dict方案 char级别"""def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded_blocks):+ page_char_count = None+ try:+ page_char_count = pdf_page.get_textpage().count_chars()+ except Exception as exc:+ logger.debug(f"Failed to get page char count before txt extraction: {exc}")++ if page_char_count is not None and page_char_count > MAX_NATIVE_TEXT_CHARS_PER_PAGE:+ logger.info(+ "Fallback to post-OCR in txt_spans_extract due to high char count: "+ f"count_chars={page_char_count}"+ )+ need_ocr_spans = [+ span for span in spans if span.get('type') == ContentType.TEXT+ ]+ return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)page_dict = get_page(pdf_page)@@ -99,21 +116,26 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discardedneed_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)- """对未填充的span进行ocr"""- if len(need_ocr_spans) > 0:+ return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)+- for span in need_ocr_spans:- # 对span的bbox截图再ocr- span_pil_img = get_crop_img(span['bbox'], pil_img, scale)- span_img = cv2.cvtColor(np.array(span_pil_img), cv2.COLOR_RGB2BGR)- # 计算span的对比度,低于0.20的span不进行ocr- if calculate_contrast(span_img, img_mode='bgr') <= 0.17:+def _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale):+ if len(need_ocr_spans) == 0:+ return spans++ for span in need_ocr_spans:+ # 对span的bbox截图再ocr+ span_pil_img = get_crop_img(span['bbox'], pil_img, scale)+ span_img = cv2.cvtColor(np.array(span_pil_img), cv2.COLOR_RGB2BGR)+ # 计算span的对比度,低于0.20的span不进行ocr+ if calculate_contrast(span_img, img_mode='bgr') <= 0.17:+ if span in spans:spans.remove(span)- continue+ continue- span['content'] = ''- span['score'] = 1.0- span['np_img'] = span_img+ span['content'] = ''+ span['score'] = 1.0+ span['np_img'] = span_imgreturn spans