-
Notifications
You must be signed in to change notification settings - Fork 4
Import of large PDFs #547
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Import of large PDFs #547
Changes from 12 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
2134522
added docling dep for ray
floschne 904e6f5
added missing pymupdf dep for ray
floschne f57d244
retry on unique violation for span texts
floschne 164e631
better error message for zip issues
floschne 67b6b05
b64 to img
floschne 9005d26
method to flush cargo steps
floschne 282d530
docling config for ray
floschne 9a94aba
docling util methods
floschne 6e7f762
docling pdf2html in ray
floschne f4d13df
docling pdf2html in RMS
floschne 63fdd73
adapted and extended pipeline for large pdf docs
floschne d9a385a
uv lock
floschne 3302220
fixed tenacity version
floschne 2217253
moved docling specific util methods to docling model
floschne d122423
removed unnecessary pymupdf from docling
floschne 6f91133
updated lock file
floschne 800605b
added missing dependency
bigabig File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
152 changes: 152 additions & 0 deletions
152
...d/src/app/preprocessing/pipeline/steps/text/init/extract_content_in_html_from_pdf_docs.py
This file contains hidden or 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,152 @@ | ||
| import math | ||
| from pathlib import Path | ||
|
|
||
| import fitz | ||
| from app.core.data.repo.repo_service import RepoService | ||
| from app.core.data.repo.utils import base64_to_image | ||
| from app.preprocessing.pipeline.model.pipeline_cargo import PipelineCargo | ||
| from app.preprocessing.pipeline.model.text.preprotextdoc import PreProTextDoc | ||
| from app.preprocessing.preprocessing_service import PreprocessingService | ||
| from app.preprocessing.ray_model_service import RayModelService | ||
| from config import conf | ||
| from loguru import logger | ||
|
|
||
| cc = conf.celery | ||
|
|
||
| repo = RepoService() | ||
| pps = PreprocessingService() | ||
| rms = RayModelService() | ||
|
|
||
|
|
||
| def __split_large_pdf_into_chunks( | ||
| input_doc: Path, max_pages_per_chunk: int = 5 | ||
| ) -> list[Path] | None: | ||
| try: | ||
| src = fitz.open(str(input_doc)) # type: ignore | ||
| total_pages = src.page_count | ||
| except Exception as e: | ||
| msg = f"Error opening PDF {input_doc.name}: {e}" | ||
| logger.error(msg) | ||
| raise RuntimeError(msg) | ||
|
|
||
| # First, we check if the PDF needs to be split | ||
| num_splits = math.ceil(total_pages / max_pages_per_chunk) | ||
| if num_splits == 1: | ||
| logger.info(f"PDF {input_doc.name} has {total_pages} pages; no split needed.") | ||
| src.close() | ||
| return None | ||
|
|
||
| # If yes, we proceed to split the PDF and save the chunks to disk in the project repo | ||
| out_dir = input_doc.parent | ||
| logger.info( | ||
| f"Splitting PDF {input_doc.name} into {num_splits} chunks of " | ||
| f"up to {max_pages_per_chunk} pages each. Output will be saved in {out_dir}." | ||
| ) | ||
|
|
||
| chunks: list[Path] = [] | ||
| for i in range(num_splits): | ||
| start_page = i * max_pages_per_chunk + 1 | ||
| end_page = min((i + 1) * max_pages_per_chunk, total_pages) | ||
| page_range_str = f"{start_page}-{end_page}" | ||
| output_fn = out_dir / f"{input_doc.stem}_pages_{page_range_str}.pdf" | ||
| try: | ||
| # Create a new PDF for the chunk | ||
| new_pdf = fitz.open() # type: ignore | ||
| new_pdf.insert_pdf(src, from_page=start_page - 1, to_page=end_page - 1) | ||
|
|
||
| # Save the chunk to disk | ||
| new_pdf.save(str(output_fn)) | ||
| new_pdf.close() | ||
| chunks.append(output_fn) | ||
|
|
||
| logger.debug(f"Stored chunk '{output_fn}'") | ||
| except Exception as e: | ||
| msg = f"Skipping due to error creating chunk {i + 1} for PDF {input_doc.name}: {e}" | ||
| logger.error(msg) | ||
| src.close() | ||
| return chunks | ||
|
|
||
|
|
||
| def __extract_content_in_html_from_pdf_docs( | ||
| filepath: Path, extract_images: bool = True | ||
| ) -> tuple[str, list[Path]]: | ||
| if not filepath.exists() or filepath.suffix != ".pdf": | ||
| logger.error(f"File {filepath} is not a PDF document!") | ||
| return "", [] | ||
|
|
||
| logger.debug(f"Extracting content as HTML from {filepath.name} ...") | ||
| pdf_bytes = filepath.read_bytes() | ||
| # this will take some time ... | ||
| conversion_output = rms.docling_pdf_to_html(pdf_bytes=pdf_bytes) | ||
| doc_html = conversion_output.html_content | ||
|
|
||
| # store all extracted images in the same directory as the PDF | ||
| extracted_images: list[Path] = [] | ||
| if extract_images: | ||
| output_path = filepath.parent | ||
| for img_fn, b64_img in conversion_output.base64_images.items(): | ||
| img_fn = Path(img_fn) | ||
| img_path = output_path / (img_fn.stem + ".png") | ||
| img = base64_to_image(b64_img) | ||
| img.save(img_path, format="PNG") | ||
| extracted_images.append(img_path) | ||
| logger.debug(f"Saved extracted image {img_path} from PDF {filepath.name}.") | ||
|
|
||
| return doc_html, extracted_images | ||
|
|
||
|
|
||
| def extract_content_in_html_from_pdf_docs( | ||
| cargo: PipelineCargo, | ||
| ) -> PipelineCargo: | ||
| ## STRATEGY: | ||
| # 0. check if PDF needs to be chunked, i.e., if it has more than N (per default 5) pages. | ||
| # YES: | ||
| # 1. Chunk the PDF | ||
| # 2. stop prepro for cargo (not the whole PPJ!) | ||
| # 3. create a new PPJ from the chunks | ||
| # NO: | ||
| # 1. continue with extracting content as HTML including images from PDF via Docling through RayModelService | ||
|
|
||
| ## TODO Open Questions: | ||
| # - how to properly link the chunks concerning the page order and SDoc links to navigate in the UI? | ||
| # - can we maybe have some sort of Parent SDoc (no Adoc!) that links the chunk sdocs? | ||
|
|
||
| pptd: PreProTextDoc = cargo.data["pptd"] | ||
| filepath = pptd.filepath | ||
|
|
||
| if filepath.suffix != ".pdf": | ||
| return cargo | ||
|
|
||
| # Split large PDFs into chunks if necessary | ||
| chunks = __split_large_pdf_into_chunks( | ||
| filepath, max_pages_per_chunk=cc.preprocessing.max_pages_per_pdf_chunk | ||
| ) | ||
|
|
||
| if chunks: | ||
| # YES -> stop prepro for cargo, start PPJ with all chunks | ||
| # (we cannot stop the whole PPJ because it might contain more payloads) | ||
| cargo._flush_next_steps() | ||
|
|
||
| logger.info(f"Starting new PPJ for {len(chunks)} PDF chunks ...") | ||
| ppj = pps.prepare_and_start_preprocessing_job_async( | ||
| proj_id=cargo.ppj_payload.project_id, | ||
| uploaded_files=None, | ||
| archive_file_path=None, | ||
| unimported_project_files=chunks, | ||
| ) | ||
| logger.info( | ||
| f"Started new PreprocessingJob {ppj.id} for {len(chunks)} PDF chunks." | ||
| ) | ||
|
|
||
| return cargo | ||
|
|
||
| # NO -> continue with extracting content as HTML from PDF | ||
| html, extracted_images = __extract_content_in_html_from_pdf_docs( | ||
| filepath, | ||
| extract_images=cc.preprocessing.extract_images_from_pdf, | ||
| ) | ||
|
|
||
| pptd.html = html | ||
| pptd.extracted_images = extracted_images | ||
|
|
||
| return cargo |
71 changes: 71 additions & 0 deletions
71
.../src/app/preprocessing/pipeline/steps/text/init/extract_content_in_html_from_word_docs.py
This file contains hidden or 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,71 @@ | ||
| from pathlib import Path | ||
| from typing import Dict, List, Tuple | ||
| from uuid import uuid4 | ||
|
|
||
| import mammoth | ||
| from app.core.data.repo.repo_service import RepoService | ||
| from app.preprocessing.pipeline.model.pipeline_cargo import PipelineCargo | ||
| from app.preprocessing.pipeline.model.text.preprotextdoc import PreProTextDoc | ||
| from config import conf | ||
| from loguru import logger | ||
|
|
||
| cc = conf.celery | ||
|
|
||
| repo = RepoService() | ||
|
|
||
|
|
||
| def __extract_content_in_html_from_word_docs(filepath: Path) -> Tuple[str, List[Path]]: | ||
| if filepath.suffix != ".docx" and filepath.suffix != ".doc": | ||
| logger.warning(f"File {filepath} is not a Word document!") | ||
| return "", [] | ||
|
|
||
| extracted_images: List[Path] = [] | ||
|
|
||
| def convert_image(image) -> Dict[str, str]: | ||
| if not cc.preprocessing.extract_images_from_docx: | ||
| return {"src": ""} | ||
|
|
||
| fn = filepath.parent / f"image_{str(uuid4())}" | ||
| if "png" in image.content_type: | ||
| fn = fn.with_suffix(".png") | ||
| elif "jpg" in image.content_type: | ||
| fn = fn.with_suffix(".jpg") | ||
| elif "jpeg" in image.content_type: | ||
| fn = fn.with_suffix(".jpeg") | ||
| else: | ||
| return {"src": ""} | ||
|
|
||
| with image.open() as image_bytes: | ||
| with open(fn, "wb") as binary_file: | ||
| binary_file.write(image_bytes.read()) | ||
| extracted_images.append(fn) | ||
| return {"src": str(fn.name)} | ||
|
|
||
| with open(str(filepath), "rb") as docx_file: | ||
| html = mammoth.convert_to_html( | ||
| docx_file, convert_image=mammoth.images.img_element(convert_image) | ||
| ) | ||
|
|
||
| return f"<html><body>{html.value}</body></html>", extracted_images | ||
|
|
||
|
|
||
| def extract_content_in_html_from_word_docs( | ||
| cargo: PipelineCargo, | ||
| ) -> PipelineCargo: | ||
| pptd: PreProTextDoc = cargo.data["pptd"] | ||
| filepath = pptd.filepath | ||
|
|
||
| if filepath.suffix not in [".docx", ".doc"]: | ||
| return cargo | ||
|
|
||
| logger.debug(f"Extracting content as HTML from {filepath.name} for ...") | ||
|
|
||
| html, extracted_images = __extract_content_in_html_from_word_docs(filepath) | ||
| extracted_images = ( | ||
| extracted_images if cc.preprocessing.extract_images_from_docx else [] | ||
| ) | ||
|
|
||
| pptd.html = html | ||
| pptd.extracted_images = extracted_images | ||
|
|
||
| return cargo |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.