-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[dev] refactor, create CustomImagePagePdfReader
- Loading branch information
zoazhyga
committed
Sep 6, 2024
1 parent
be204cf
commit 800127f
Showing
3 changed files
with
54 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import logging | ||
from typing import Any, Dict, List, Optional | ||
import tqdm | ||
|
||
from llama_index.core.readers.base import BaseReader | ||
from llama_index.core.schema import Document | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class CustomImagePagePdfReader(BaseReader): | ||
def __init__(self, *args: Any, lang: str = "rus", **kwargs: Any) -> None: | ||
super().__init__(*args, **kwargs) | ||
|
||
self.lang = lang | ||
|
||
def load_data( | ||
self, pdf_path: str, extra_info: Optional[Dict] = None | ||
) -> List[Document]: | ||
|
||
try: | ||
import pdf2image | ||
except ImportError: | ||
raise ImportError("You need to install `pdf2image` to use this reader") | ||
|
||
try: | ||
import pytesseract | ||
except ImportError: | ||
raise ImportError("You need to install `pytesseract` to use this reader") | ||
|
||
images = pdf2image.convert_from_path(pdf_path) | ||
documents = [] | ||
|
||
for i, image in tqdm.tqdm(enumerate(images)): | ||
text = pytesseract.image_to_string(image, lang=self.lang) | ||
doc = Document( | ||
text=text, | ||
extra_info={"chunk_type": "image", "page_label": i + 1}, | ||
) | ||
documents.append(doc) | ||
|
||
return documents |