|
| 1 | +from typing import List, Tuple, Dict, Any |
| 2 | +from docling.document_converter import DocumentConverter as DoclingConverter, PdfFormatOption |
| 3 | +from docling.datamodel.pipeline_options import PdfPipelineOptions, OcrMacOptions |
| 4 | +from docling.datamodel.base_models import InputFormat |
| 5 | +import fitz # PyMuPDF for quick text inspection |
| 6 | +import os |
| 7 | + |
| 8 | +class DocumentConverter: |
| 9 | + """ |
| 10 | + A class to convert various document formats to structured Markdown using the docling library. |
| 11 | + Supports PDF, DOCX, HTML, and other formats. |
| 12 | + """ |
| 13 | + |
| 14 | + # Mapping of file extensions to InputFormat |
| 15 | + SUPPORTED_FORMATS = { |
| 16 | + '.pdf': InputFormat.PDF, |
| 17 | + '.docx': InputFormat.DOCX, |
| 18 | + '.html': InputFormat.HTML, |
| 19 | + '.htm': InputFormat.HTML, |
| 20 | + } |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + """Initializes the docling document converter with forced OCR enabled for macOS.""" |
| 24 | + try: |
| 25 | + # --- Converter WITHOUT OCR (fast path) --- |
| 26 | + pipeline_no_ocr = PdfPipelineOptions() |
| 27 | + pipeline_no_ocr.do_ocr = False |
| 28 | + format_no_ocr = { |
| 29 | + InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_no_ocr) |
| 30 | + } |
| 31 | + self.converter_no_ocr = DoclingConverter(format_options=format_no_ocr) |
| 32 | + |
| 33 | + # --- Converter WITH OCR (fallback) --- |
| 34 | + pipeline_ocr = PdfPipelineOptions() |
| 35 | + pipeline_ocr.do_ocr = True |
| 36 | + ocr_options = OcrMacOptions(force_full_page_ocr=True) |
| 37 | + pipeline_ocr.ocr_options = ocr_options |
| 38 | + format_ocr = { |
| 39 | + InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_ocr) |
| 40 | + } |
| 41 | + self.converter_ocr = DoclingConverter(format_options=format_ocr) |
| 42 | + |
| 43 | + self.converter_general = DoclingConverter() |
| 44 | + |
| 45 | + print("docling DocumentConverter(s) initialized (OCR + no-OCR + general).") |
| 46 | + except Exception as e: |
| 47 | + print(f"Error initializing docling DocumentConverter(s): {e}") |
| 48 | + self.converter_no_ocr = None |
| 49 | + self.converter_ocr = None |
| 50 | + self.converter_general = None |
| 51 | + |
| 52 | + def convert_to_markdown(self, file_path: str) -> List[Tuple[str, Dict[str, Any]]]: |
| 53 | + """ |
| 54 | + Converts a document to a single Markdown string, preserving layout and tables. |
| 55 | + Supports PDF, DOCX, HTML, and other formats. |
| 56 | + """ |
| 57 | + if not (self.converter_no_ocr and self.converter_ocr and self.converter_general): |
| 58 | + print("docling converters not available. Skipping conversion.") |
| 59 | + return [] |
| 60 | + |
| 61 | + file_ext = os.path.splitext(file_path)[1].lower() |
| 62 | + if file_ext not in self.SUPPORTED_FORMATS: |
| 63 | + print(f"Unsupported file format: {file_ext}") |
| 64 | + return [] |
| 65 | + |
| 66 | + input_format = self.SUPPORTED_FORMATS[file_ext] |
| 67 | + |
| 68 | + if input_format == InputFormat.PDF: |
| 69 | + return self._convert_pdf_to_markdown(file_path) |
| 70 | + else: |
| 71 | + return self._convert_general_to_markdown(file_path, input_format) |
| 72 | + |
| 73 | + def _convert_pdf_to_markdown(self, pdf_path: str) -> List[Tuple[str, Dict[str, Any]]]: |
| 74 | + """Convert PDF with OCR detection logic.""" |
| 75 | + # Quick heuristic: if the PDF already contains a text layer, skip OCR for speed |
| 76 | + def _pdf_has_text(path: str) -> bool: |
| 77 | + try: |
| 78 | + doc = fitz.open(path) |
| 79 | + for page in doc: |
| 80 | + if page.get_text("text").strip(): |
| 81 | + return True |
| 82 | + except Exception: |
| 83 | + pass |
| 84 | + return False |
| 85 | + |
| 86 | + use_ocr = not _pdf_has_text(pdf_path) |
| 87 | + converter = self.converter_ocr if use_ocr else self.converter_no_ocr |
| 88 | + ocr_msg = "(OCR enabled)" if use_ocr else "(no OCR)" |
| 89 | + |
| 90 | + print(f"Converting {pdf_path} to Markdown using docling {ocr_msg}...") |
| 91 | + return self._perform_conversion(pdf_path, converter, ocr_msg) |
| 92 | + |
| 93 | + def _convert_general_to_markdown(self, file_path: str, input_format: InputFormat) -> List[Tuple[str, Dict[str, Any]]]: |
| 94 | + """Convert non-PDF formats using general converter.""" |
| 95 | + print(f"Converting {file_path} ({input_format.name}) to Markdown using docling...") |
| 96 | + return self._perform_conversion(file_path, self.converter_general, f"({input_format.name})") |
| 97 | + |
| 98 | + def _perform_conversion(self, file_path: str, converter, format_msg: str) -> List[Tuple[str, Dict[str, Any]]]: |
| 99 | + """Perform the actual conversion using the specified converter.""" |
| 100 | + pages_data = [] |
| 101 | + try: |
| 102 | + result = converter.convert(file_path) |
| 103 | + markdown_content = result.document.export_to_markdown() |
| 104 | + |
| 105 | + metadata = {"source": file_path} |
| 106 | + # Return the *DoclingDocument* object as third tuple element so downstream |
| 107 | + # chunkers that understand the element tree can use it. Legacy callers that |
| 108 | + # expect only (markdown, metadata) can simply ignore the extra value. |
| 109 | + pages_data.append((markdown_content, metadata, result.document)) |
| 110 | + print(f"Successfully converted {file_path} with docling {format_msg}.") |
| 111 | + return pages_data |
| 112 | + except Exception as e: |
| 113 | + print(f"Error processing {file_path} with docling: {e}") |
| 114 | + return [] |
0 commit comments