Repository navigation
[Data] Adding ray.data.read_pdf - #57239
soffer-anyscale wants to merge 12 commits into
Conversation
Implements comprehensive PDF reading capabilities: - PDFDatasource class for reading PDF files - Page-level and document-level reading modes - OCR support for image-based/scanned PDFs - Image extraction from PDF pages - Document metadata extraction (title, author, dates) - Comprehensive test suite with 20+ test cases - BUILD.bazel integration - Full documentation and docstrings Files added: - python/ray/data/_internal/datasource/pdf_datasource.py - python/ray/data/tests/test_pdf.py Files modified: - python/ray/data/read_api.py (added read_pdfs function) - python/ray/data/BUILD.bazel (added test_pdf target) Signed-off-by: soffer-anyscale <[email protected]>
Adds control over block sizing for very large PDF files: - max_pages_per_block parameter in read_pdfs() and PDFDatasource - Batches pages into blocks to reduce memory overhead - Example: 500-page PDF with max_pages_per_block=10 creates 50 blocks - Validation: requires pages=True, must be positive - Comprehensive tests for batching behavior - Documentation with examples for large PDF handling This helps users efficiently process PDFs with hundreds or thousands of pages without memory issues or excessive block creation overhead. Signed-off-by: soffer-anyscale <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a comprehensive ray.data.read_pdfs() function, which is a great addition to Ray Data's capabilities. The implementation is thorough, covering various modes of reading, metadata extraction, and OCR support. The tests are also quite comprehensive.
My review focuses on a few areas for improvement regarding code maintainability, use of private APIs, and a minor bug in the tests. Specifically, I've pointed out opportunities to reduce code duplication, replace a risky private API call with a safer alternative, and correct a test assertion.
Overall, this is a solid contribution. Addressing these points will make the code more robust and easier to maintain.
| # Convert page to image | ||
| # Note: This requires poppler to be installed | ||
| images = convert_from_bytes( | ||
| page._pdf.write_bytes(), |
There was a problem hiding this comment.
The use of the private attribute page._pdf is risky, as it's not part of PyPDF2's public API and could break in future updates. Additionally, page._pdf.write_bytes() re-writes the entire PDF file to a byte stream for each page being processed with OCR, which is inefficient.
A safer and more performant approach is to pass the PDF file's byte data, which is already available in _read_stream, down to _ocr_page.
Here's a suggested refactoring:
- In
_read_stream, pass thedatabytes to_read_pages. - Propagate the
databytes through_read_pages->_extract_text_from_page->_ocr_page. - In
_ocr_page, use the passed-indatabytes directly withconvert_from_bytesinstead of callingpage._pdf.write_bytes().
This will avoid the private API usage and improve performance by not re-generating the PDF bytes for every page.
| def _get_block_metadata( | ||
| self, | ||
| paths: List[str], | ||
| schema: Optional[Any], | ||
| **kwargs, | ||
| ) -> Any: | ||
| """Get block metadata with custom encoding ratio applied.""" | ||
| metadata = super()._get_block_metadata(paths, schema, **kwargs) | ||
| return metadata |
There was a problem hiding this comment.
| def test_file_metadata_provider(self, tmp_path): | ||
| """Test PDFFileMetadataProvider.""" | ||
| provider = PDFFileMetadataProvider() | ||
| assert provider._get_file_extension() == "pdf" |
There was a problem hiding this comment.
This assertion is incorrect. PDFFileMetadataProvider inherits _get_file_extension from DefaultFileMetadataProvider, which returns None. The _FILE_EXTENSIONS attribute is defined on PDFDatasource, not the metadata provider. This test will fail.
To fix this, you could either remove this test or test this behavior on a PDFDatasource instance.
| assert provider._get_file_extension() == "pdf" | |
| assert provider._get_file_extension() is None |
- Fix OCR method to accept page_num and pdf_bytes instead of using non-existent page._pdf and page.page_number attributes - Fix image extraction to check for /Resources existence before accessing to prevent KeyError - Refactor _read_pages to extract common page processing logic into _process_page_data helper method - Remove use of private API page._pdf by passing PDF bytes from _read_stream through the call chain - Remove redundant _get_block_metadata method from PDFFileMetadataProvider - Fix test assertion for _get_file_extension to expect None instead of 'pdf' - Fix import ordering in read_api.py and test_pdf.py Signed-off-by: soffer-anyscale <[email protected]>
Fix bug where _extract_text_from_page was called with only page argument but expects page, page_num, and pdf_bytes after recent refactoring. This caused TypeError when processing PDFs in document-level mode (pages=False). Signed-off-by: soffer-anyscale <[email protected]>
- Add missing pdf2image dependency check when ocr=True in PDFDatasource constructor - Update docstring to mention pdf2image as required dependency for OCR - Fix test_file_metadata_provider test that was checking for non-existent _get_file_extension() method - Rename test to test_pdf_file_metadata_provider_initialization to avoid duplicate name - Test now validates PDFFileMetadataProvider inheritance and encoding ratio initialization Signed-off-by: soffer-anyscale <[email protected]>
Signed-off-by: soffer-anyscale <[email protected]>
- Add PyPDF2 to data-test-requirements.txt for PDF reading tests - Fix RST formatting in arrow_open_file_args URL (remove incorrect indentation) - Add doctest: +SKIP to all read_pdfs examples to prevent CI execution - Fixes module not found error in test_pdf.py - Fixes RST doc build errors (unexpected indentation, missing end-string) Signed-off-by: soffer-anyscale <[email protected]>
Fixed three critical bugs in PDF datasource: 1. TypeError: object of type 'method' has no len() - Fixed by calling self._paths() instead of using self._paths directly - The _paths property is a method that returns the list of paths 2. Per-file timeout causing long estimation delays - Moved start_time outside the file iteration loop - Timeout now applies globally across all files, not per-file - This prevents the estimation from taking 10s per file 3. Doctest error with inline directive on comment line - Removed '# doctest: +SKIP' from comment-only lines - Doctest directives should only be on lines with code examples All bugs validated and lint checks passing. Signed-off-by: Stephen Offer <[email protected]> Signed-off-by: soffer-anyscale <[email protected]>
f6514e8 to
d273c36
Compare
Signed-off-by: soffer-anyscale <[email protected]>
This commit enhances the PDF datasource implementation to follow Ray coding standards
and improves overall code quality:
1. Fixed test_corrupted_pdf_handling failure:
- Changed corrupted PDF handling from raising ValueError to graceful skip with warning
- Files that cannot be read (corrupted, password-protected) are now logged and skipped
- This allows dataset processing to continue instead of crashing
2. Improved code structure and modularity:
- Split large _estimate_files_encoding_ratio() method into three smaller functions:
* _estimate_single_file_ratio() - handles single file estimation
* _calculate_median_ratio() - calculates median from samples
* _estimate_files_encoding_ratio() - orchestrates the overall process
- Each function now has a single, well-defined responsibility
- Reduced function complexity and improved testability
3. Enhanced documentation:
- Fixed pydoclint errors by adding proper yield type annotations
- All docstrings now follow Ray's documentation standards
- Added inline comments explaining complex logic
- Improved method descriptions for clarity
4. Code quality improvements:
- Naming conventions follow Python standards (snake_case, PascalCase, UPPER_SNAKE_CASE)
- Proper use of type hints throughout
- Error handling with appropriate logging levels
- Constants defined at module level
- Good separation of concerns between methods
5. Passed all linting checks:
- ruff (formatting and style)
- black (code formatting)
- pydoclint (docstring validation)
- Ray docstyle violations
- Ray import order
- All other pre-commit hooks
The code now follows best practices for:
- Function size (no functions exceed reasonable complexity)
- Clear naming conventions
- Comprehensive documentation
- Proper error handling
- Good modularity and organization
Signed-off-by: soffer-anyscale <[email protected]>
… handling This commit addresses critical architectural issues discovered during thorough audit: 1. Fixed PDFFileMetadataProvider missing _get_block_metadata override: - Added _get_block_metadata() method to properly apply encoding ratio - This method was missing, causing incorrect size estimates for memory planning - Now matches pattern used by ImageFileMetadataProvider - Import BlockMetadata from ray.data.block for proper type annotations 2. Updated read_pdfs() documentation: - Changed Raises section to note that corrupted PDFs are skipped with warning - Added explicit note about graceful handling of invalid files - Removed incorrect ValueError documentation for corrupted files - Now accurately reflects the actual behavior Audit findings validated: - ✓ Follows FileBasedDatasource patterns correctly - ✓ Proper inheritance and base class usage - ✓ PyPDF2 integration follows best practices (local imports, error handling) - ✓ Parameter handling in read_api.py is correct - ✓ Comprehensive test coverage (28 tests covering all features) - ✓ All pre-commit lint checks pass - ✓ Naming conventions follow Ray standards - ✓ Error handling is graceful and user-friendly The implementation now correctly follows Ray Data architecture and matches the patterns established by similar datasources (image, audio, video). Signed-off-by: soffer-anyscale <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
Reduced file from 717 to 381 lines (~47% reduction) by: - Shortening verbose docstrings to match other datasources - Consolidating metadata extraction with loop - Simplifying encoding ratio estimation - Removing redundant comments and explanations - Using list comprehensions where appropriate - Consolidating error handling Signed-off-by: soffer-anyscale <[email protected]>
## Description Style and grammar pass on Ray Data docs against Ray's [writing-style guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html). Prose only: no code, `literalinclude` blocks, URLs, anchors, or role targets changed. Stacked on #66412, which is stacked on #66381, #66375, and #66352. Review and merge those first. This branch targets `doc-1524-data-vale-cleanup`. It combines this PR's original comparisons-page pass with the custom datasource pass first opened as #66416. ### `comparisons.md` - Renames the legacy "Datasets" product name to "Ray Data". The page already used "Ray Data" for the same subject in the same lists. Third-party "Torch datasets" and "TensorFlow datasets" are unchanged. - Fixes `SageMaker` and `BentoML` casing, which #66412 left as intentional alerts for this pass. - Uses contractions, active voice, second person, and "such as" for examples. - Removes "our blog post", "3rd", "e.g.", mid-sentence colons, and semicolons. - Fixes the grammar of the BentoML-and-Spark sentence and subject-verb agreement for "TensorFlow datasets". - Sentence-cases the dropdown titles and makes them parallel. - Adds a lead-in sentence to each comparison list and uses the `**Term**: explanation` definition-list form from the style guide. - Collapses runs of blank lines between dropdowns to one. ### `custom-datasource-example.md` This is the page whose `<!-- vale off -->` blocks #66412 removed so the future-tense prose they hid could be fixed. - Replaces the three "you'll" future-tense sentences with present tense. - Names Ray Data as the actor in "file types that aren't natively supported" and "Images are already supported". - Replaces "functionality" with "behavior", "Once you've implemented" with "After you implement", and the "(for example, `"png"`)" parenthetical with "such as". - Cuts the time-relative "in the future" from the write-interface note but keeps "is under active development and might change", which is the stability warning. - Corrects the block types. The page said blocks can be dictionaries of NumPy arrays, but `Block` in `block.py` is only a PyArrow table or a pandas DataFrame, including at the commit the page links to. NumPy dictionaries are a batch format. This is a factual correction. - Sentence-cases the title: "Advanced: Read and write custom file types". - Updates the one link in `loading-data.md` whose text quotes the old title. ## Why this isn't a duplicate No other open PR edits `comparisons.md`, `custom-datasource-example.md`, or `doc_code/custom_datasource_example.py`. #55038 adds an experimental SQL API and SQL docs but doesn't edit these pages. See the related question below. I also checked the open Data PRs that mention datasources, including #65760, #57239, and #55467. ## Questions for reviewers Apart from the block-types correction, this pass kept the scope of every claim. These existing claims might be stale, and a Ray Data maintainer is better placed to judge them: - **Third-party feature claims on `comparisons.md`:** Petastorm supports only Parquet, NVTabular supports only Parquet, CSV, and Avro, TensorFlow datasets support only file interleaving across worker shards, and Torch datasets have no I/O layer. - **SQL interface:** "Ray Data doesn't have a SQL interface" would go stale if #55038 lands. - **Comparisons with no measure:** "a streaming paradigm that's better suited to GPU workloads" and "can't effectively handle large datasets". The style guide's "Keep comparisons precise" section applies, but no source for a measure is on the page. - **Repeated comparison points:** the training-ingest dropdowns repeat three points almost word for word. A single comparison table might read better. That moves content, so it isn't in this PR. - **Duplicate headings:** `custom-datasource-example.md` has two H3s named "Implement the constructor", one under reading and one under writing. "Implement the datasource constructor" and "Implement the datasink constructor" would make the right-side TOC clearer. I left them as they are. ## Verification - `vale` with Vale 3.12, run from the repo root: 0 alerts on `comparisons.md`, down from 24, and 0 on `custom-datasource-example.md`, down from 6. `loading-data.md` has no alerts on the edited line. - `codespell`: no hits. - The pre-commit hooks passed on each commit. - A structural check against each pre-edit file confirmed the code-fence count, role targets, anchors, and URLs are unchanged. - For the reworded title, a grep for inbound links found the `{ref}` in `loading-data.md`, updated here, and a toctree entry in `user-guide.md`, which doesn't depend on the title. No links use the heading's implicit slug. - I didn't run a local Sphinx build. The Read the Docs preview covers rendering. ## AI assistance I made these edits with AI assistance (Claude Code) and reviewed the full diff by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
## Description Style and grammar pass on Ray Data docs against Ray's [writing-style guide](https://docs.ray.io/en/master/ray-contribute/writing-style.html). Prose only: no code, `literalinclude` blocks, URLs, anchors, or role targets changed. Stacked on ray-project#66412, which is stacked on ray-project#66381, ray-project#66375, and ray-project#66352. Review and merge those first. This branch targets `doc-1524-data-vale-cleanup`. It combines this PR's original comparisons-page pass with the custom datasource pass first opened as ray-project#66416. ### `comparisons.md` - Renames the legacy "Datasets" product name to "Ray Data". The page already used "Ray Data" for the same subject in the same lists. Third-party "Torch datasets" and "TensorFlow datasets" are unchanged. - Fixes `SageMaker` and `BentoML` casing, which ray-project#66412 left as intentional alerts for this pass. - Uses contractions, active voice, second person, and "such as" for examples. - Removes "our blog post", "3rd", "e.g.", mid-sentence colons, and semicolons. - Fixes the grammar of the BentoML-and-Spark sentence and subject-verb agreement for "TensorFlow datasets". - Sentence-cases the dropdown titles and makes them parallel. - Adds a lead-in sentence to each comparison list and uses the `**Term**: explanation` definition-list form from the style guide. - Collapses runs of blank lines between dropdowns to one. ### `custom-datasource-example.md` This is the page whose `<!-- vale off -->` blocks ray-project#66412 removed so the future-tense prose they hid could be fixed. - Replaces the three "you'll" future-tense sentences with present tense. - Names Ray Data as the actor in "file types that aren't natively supported" and "Images are already supported". - Replaces "functionality" with "behavior", "Once you've implemented" with "After you implement", and the "(for example, `"png"`)" parenthetical with "such as". - Cuts the time-relative "in the future" from the write-interface note but keeps "is under active development and might change", which is the stability warning. - Corrects the block types. The page said blocks can be dictionaries of NumPy arrays, but `Block` in `block.py` is only a PyArrow table or a pandas DataFrame, including at the commit the page links to. NumPy dictionaries are a batch format. This is a factual correction. - Sentence-cases the title: "Advanced: Read and write custom file types". - Updates the one link in `loading-data.md` whose text quotes the old title. ## Why this isn't a duplicate No other open PR edits `comparisons.md`, `custom-datasource-example.md`, or `doc_code/custom_datasource_example.py`. ray-project#55038 adds an experimental SQL API and SQL docs but doesn't edit these pages. See the related question below. I also checked the open Data PRs that mention datasources, including ray-project#65760, ray-project#57239, and ray-project#55467. ## Questions for reviewers Apart from the block-types correction, this pass kept the scope of every claim. These existing claims might be stale, and a Ray Data maintainer is better placed to judge them: - **Third-party feature claims on `comparisons.md`:** Petastorm supports only Parquet, NVTabular supports only Parquet, CSV, and Avro, TensorFlow datasets support only file interleaving across worker shards, and Torch datasets have no I/O layer. - **SQL interface:** "Ray Data doesn't have a SQL interface" would go stale if ray-project#55038 lands. - **Comparisons with no measure:** "a streaming paradigm that's better suited to GPU workloads" and "can't effectively handle large datasets". The style guide's "Keep comparisons precise" section applies, but no source for a measure is on the page. - **Repeated comparison points:** the training-ingest dropdowns repeat three points almost word for word. A single comparison table might read better. That moves content, so it isn't in this PR. - **Duplicate headings:** `custom-datasource-example.md` has two H3s named "Implement the constructor", one under reading and one under writing. "Implement the datasource constructor" and "Implement the datasink constructor" would make the right-side TOC clearer. I left them as they are. ## Verification - `vale` with Vale 3.12, run from the repo root: 0 alerts on `comparisons.md`, down from 24, and 0 on `custom-datasource-example.md`, down from 6. `loading-data.md` has no alerts on the edited line. - `codespell`: no hits. - The pre-commit hooks passed on each commit. - A structural check against each pre-edit file confirmed the code-fence count, role targets, anchors, and URLs are unchanged. - For the reworded title, a grep for inbound links found the `{ref}` in `loading-data.md`, updated here, and a toctree entry in `user-guide.md`, which doesn't depend on the title. No links use the heading's implicit slug. - I didn't run a local Sphinx build. The Read the Docs preview covers rendering. ## AI assistance I made these edits with AI assistance (Claude Code) and reviewed the full diff by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This PR adds comprehensive PDF reading capabilities to Ray Data through the new
ray.data.read_pdfs()function. This enables users to efficiently read and process PDF documents at scale for AI/ML workflows, including RAG (Retrieval-Augmented Generation) applications, document processing pipelines, and batch PDF analysis.Key Features:
Flexible Reading Modes
max_pages_per_blockfor large PDFsAdvanced Text Extraction
Rich Metadata
Performance & Scalability
max_pages_per_blockparameter for controlling block size in large PDFsImplementation:
FileBasedDatasourcewith full PDF parsing logicUse Case Examples:
This feature fills a gap in Ray Data's file reading capabilities and enables efficient PDF processing workflows at scale.
Related issue number
N/A - New feature request implementation
Checks
git commit -s) in this PR.read_pdfs()API is documented with comprehensive docstringstest_pdf.py)Testing Coverage:
max_pages_per_block