|
| 1 | +import asyncio |
| 2 | +from pathlib import Path |
| 3 | +from typing import Any, Callable, Dict, List, Optional, Union |
| 4 | + |
| 5 | +import fitz |
| 6 | +from fitz import Document as FitzDocument |
| 7 | + |
| 8 | +try: |
| 9 | + from llama_index.core.readers.base import BaseReader |
| 10 | + from llama_index.core.schema import Document as LlamaIndexDocument |
| 11 | + |
| 12 | + print("All imports are successful.") |
| 13 | +except ImportError: |
| 14 | + raise NotImplementedError("Please install 'llama_index' is needed.") |
| 15 | + |
| 16 | + |
| 17 | +import pymupdf4llm |
| 18 | + |
| 19 | + |
| 20 | +class PDFMardownReader(BaseReader): |
| 21 | + """Read PDF files using PyMuPDF library.""" |
| 22 | + |
| 23 | + use_doc_meta: bool = True |
| 24 | + meta_filter: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + use_doc_meta: bool = True, |
| 29 | + meta_filter: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None, |
| 30 | + ): |
| 31 | + self.use_doc_meta = use_doc_meta |
| 32 | + self.meta_filter = meta_filter |
| 33 | + |
| 34 | + def load_data( |
| 35 | + self, |
| 36 | + file_path: Union[Path, str], |
| 37 | + extra_info: Optional[Dict] = None, |
| 38 | + **load_kwargs: Any, |
| 39 | + ) -> List[LlamaIndexDocument]: |
| 40 | + """Loads list of documents from PDF file and also accepts extra information in dict format. |
| 41 | +
|
| 42 | + Args: |
| 43 | + file_path (Union[Path, str]): The path to the PDF file. |
| 44 | + extra_info (Optional[Dict], optional): A dictionary containing extra information. Defaults to None. |
| 45 | + **load_kwargs (Any): Additional keyword arguments to be passed to the load method. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + List[LlamaIndexDocument]: A list of LlamaIndexDocument objects. |
| 49 | + """ |
| 50 | + if not isinstance(file_path, str) and not isinstance(file_path, Path): |
| 51 | + raise TypeError("file_path must be a string or Path.") |
| 52 | + |
| 53 | + if not extra_info: |
| 54 | + extra_info = {} |
| 55 | + |
| 56 | + if extra_info and not isinstance(extra_info, dict): |
| 57 | + raise TypeError("extra_info must be a dictionary.") |
| 58 | + |
| 59 | + doc: FitzDocument = fitz.open(file_path) |
| 60 | + |
| 61 | + docs = [] |
| 62 | + for page in doc: |
| 63 | + docs.append(self._process_doc_page(doc, extra_info, file_path, page.number)) |
| 64 | + return docs |
| 65 | + |
| 66 | + async def aload_data( |
| 67 | + self, |
| 68 | + file_path: Union[Path, str], |
| 69 | + extra_info: Optional[Dict] = None, |
| 70 | + **load_kwargs: Any, |
| 71 | + ) -> List[LlamaIndexDocument]: |
| 72 | + """Asynchronously loads list of documents from PDF file and also accepts extra information in dict format. |
| 73 | +
|
| 74 | + Args: |
| 75 | + file_path (Union[Path, str]): The path to the PDF file. |
| 76 | + extra_info (Optional[Dict], optional): A dictionary containing extra information. Defaults to None. |
| 77 | + **load_kwargs (Any): Additional keyword arguments to be passed to the load method. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + List[LlamaIndexDocument]: A list of LlamaIndexDocument objects. |
| 81 | + """ |
| 82 | + if not isinstance(file_path, str) and not isinstance(file_path, Path): |
| 83 | + raise TypeError("file_path must be a string or Path.") |
| 84 | + |
| 85 | + if not extra_info: |
| 86 | + extra_info = {} |
| 87 | + |
| 88 | + if extra_info and not isinstance(extra_info, dict): |
| 89 | + raise TypeError("extra_info must be a dictionary.") |
| 90 | + |
| 91 | + doc: FitzDocument = fitz.open(file_path) |
| 92 | + |
| 93 | + tasks = [] |
| 94 | + for page in doc: |
| 95 | + tasks.append( |
| 96 | + self._process_doc_page(doc, extra_info, file_path, page.number) |
| 97 | + ) |
| 98 | + return await asyncio.gather(*tasks) |
| 99 | + |
| 100 | + # Helpers |
| 101 | + # --- |
| 102 | + |
| 103 | + def _process_doc_page( |
| 104 | + self, |
| 105 | + doc: FitzDocument, |
| 106 | + extra_info: Dict[str, Any], |
| 107 | + file_path: str, |
| 108 | + page_number: int, |
| 109 | + ): |
| 110 | + """Processes a single page of a PDF document.""" |
| 111 | + if self.use_doc_meta: |
| 112 | + extra_info = self._process_doc_meta(doc, file_path, page_number, extra_info) |
| 113 | + |
| 114 | + if self.meta_filter: |
| 115 | + extra_info = self.meta_filter(extra_info) |
| 116 | + |
| 117 | + text = pymupdf4llm.to_markdown(doc, [page_number]) |
| 118 | + return LlamaIndexDocument(text=text, extra_info=extra_info) |
| 119 | + |
| 120 | + def _process_doc_meta( |
| 121 | + self, |
| 122 | + doc: FitzDocument, |
| 123 | + file_path: Union[Path, str], |
| 124 | + page_number: int, |
| 125 | + extra_info: Optional[Dict] = None, |
| 126 | + ): |
| 127 | + """Processes metas of a PDF document.""" |
| 128 | + extra_info.update(doc.metadata) |
| 129 | + extra_info["page_number"] = f"{page_number+1}" |
| 130 | + extra_info["total_pages"] = len(doc) |
| 131 | + extra_info["file_path"] = str(file_path) |
| 132 | + |
| 133 | + return extra_info |
0 commit comments