natural-pdf 0.1.6__py3-none-any.whl → 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. docs/categorizing-documents/index.md +168 -0
  2. docs/data-extraction/index.md +87 -0
  3. docs/element-selection/index.ipynb +218 -164
  4. docs/element-selection/index.md +20 -0
  5. docs/finetuning/index.md +176 -0
  6. docs/index.md +19 -0
  7. docs/ocr/index.md +63 -16
  8. docs/tutorials/01-loading-and-extraction.ipynb +411 -248
  9. docs/tutorials/02-finding-elements.ipynb +123 -46
  10. docs/tutorials/03-extracting-blocks.ipynb +24 -19
  11. docs/tutorials/04-table-extraction.ipynb +17 -12
  12. docs/tutorials/05-excluding-content.ipynb +37 -32
  13. docs/tutorials/06-document-qa.ipynb +36 -31
  14. docs/tutorials/07-layout-analysis.ipynb +45 -40
  15. docs/tutorials/07-working-with-regions.ipynb +61 -60
  16. docs/tutorials/08-spatial-navigation.ipynb +76 -71
  17. docs/tutorials/09-section-extraction.ipynb +160 -155
  18. docs/tutorials/10-form-field-extraction.ipynb +71 -66
  19. docs/tutorials/11-enhanced-table-processing.ipynb +11 -6
  20. docs/tutorials/12-ocr-integration.ipynb +3420 -312
  21. docs/tutorials/12-ocr-integration.md +68 -106
  22. docs/tutorials/13-semantic-search.ipynb +641 -251
  23. natural_pdf/__init__.py +3 -0
  24. natural_pdf/analyzers/layout/gemini.py +63 -47
  25. natural_pdf/classification/manager.py +343 -0
  26. natural_pdf/classification/mixin.py +149 -0
  27. natural_pdf/classification/results.py +62 -0
  28. natural_pdf/collections/mixins.py +63 -0
  29. natural_pdf/collections/pdf_collection.py +326 -17
  30. natural_pdf/core/element_manager.py +73 -4
  31. natural_pdf/core/page.py +255 -83
  32. natural_pdf/core/pdf.py +385 -367
  33. natural_pdf/elements/base.py +1 -3
  34. natural_pdf/elements/collections.py +279 -49
  35. natural_pdf/elements/region.py +106 -21
  36. natural_pdf/elements/text.py +5 -2
  37. natural_pdf/exporters/__init__.py +4 -0
  38. natural_pdf/exporters/base.py +61 -0
  39. natural_pdf/exporters/paddleocr.py +345 -0
  40. natural_pdf/extraction/manager.py +134 -0
  41. natural_pdf/extraction/mixin.py +246 -0
  42. natural_pdf/extraction/result.py +37 -0
  43. natural_pdf/ocr/__init__.py +16 -8
  44. natural_pdf/ocr/engine.py +46 -30
  45. natural_pdf/ocr/engine_easyocr.py +86 -42
  46. natural_pdf/ocr/engine_paddle.py +39 -28
  47. natural_pdf/ocr/engine_surya.py +32 -16
  48. natural_pdf/ocr/ocr_factory.py +34 -23
  49. natural_pdf/ocr/ocr_manager.py +98 -34
  50. natural_pdf/ocr/ocr_options.py +38 -10
  51. natural_pdf/ocr/utils.py +59 -33
  52. natural_pdf/qa/document_qa.py +0 -4
  53. natural_pdf/selectors/parser.py +363 -238
  54. natural_pdf/templates/finetune/fine_tune_paddleocr.md +420 -0
  55. natural_pdf/utils/debug.py +4 -2
  56. natural_pdf/utils/identifiers.py +9 -5
  57. natural_pdf/utils/locks.py +8 -0
  58. natural_pdf/utils/packaging.py +172 -105
  59. natural_pdf/utils/text_extraction.py +96 -65
  60. natural_pdf/utils/tqdm_utils.py +43 -0
  61. natural_pdf/utils/visualization.py +1 -1
  62. {natural_pdf-0.1.6.dist-info → natural_pdf-0.1.8.dist-info}/METADATA +10 -3
  63. {natural_pdf-0.1.6.dist-info → natural_pdf-0.1.8.dist-info}/RECORD +66 -51
  64. {natural_pdf-0.1.6.dist-info → natural_pdf-0.1.8.dist-info}/WHEEL +1 -1
  65. {natural_pdf-0.1.6.dist-info → natural_pdf-0.1.8.dist-info}/licenses/LICENSE +0 -0
  66. {natural_pdf-0.1.6.dist-info → natural_pdf-0.1.8.dist-info}/top_level.txt +0 -0
@@ -141,6 +141,26 @@ page.find_all('text:bold').show()
141
141
  page.find_all('text[size>=11]:bold')
142
142
  ```
143
143
 
144
+ ### Negation Pseudo-class (`:not()`)
145
+
146
+ You can exclude elements that match a certain selector using the `:not()` pseudo-class. It takes another simple selector as its argument.
147
+
148
+ ```python
149
+ # Find all text elements that are NOT bold
150
+ non_bold_text = page.find_all('text:not(:bold)')
151
+
152
+ # Find all elements that are NOT regions of type 'table'
153
+ not_tables = page.find_all(':not(region[type=table])')
154
+
155
+ # Find text elements that do not contain "Total" (case-insensitive)
156
+ relevant_text = page.find_all('text:not(:contains("Total"))', case=False)
157
+
158
+ # Find text elements that are not empty
159
+ non_empty_text = page.find_all('text:not(:empty)')
160
+ ```
161
+
162
+ **Note:** The selector inside `:not()` follows the same rules as regular selectors but currently does not support combinators (like `>`, `+`, `~`, or descendant space) within `:not()`. You can nest basic type, attribute, and other pseudo-class selectors.
163
+
144
164
  ### Spatial Pseudo-Classes Examples
145
165
 
146
166
  ```python
@@ -0,0 +1,176 @@
1
+ # OCR Fine-tuning
2
+
3
+ While the built-in OCR engines (EasyOCR, PaddleOCR, Surya) offer good general performance, you might encounter situations where their accuracy isn't sufficient for your specific needs. This is often the case with:
4
+
5
+ * **Unique Fonts:** Documents using unusual or stylized fonts.
6
+ * **Specific Languages:** Languages or scripts not perfectly covered by the default models.
7
+ * **Low Quality Scans:** Noisy or degraded document images.
8
+ * **Specialized Layouts:** Text within complex tables, forms, or unusual arrangements.
9
+
10
+ Fine-tuning allows you to adapt a pre-trained OCR recognition model to your specific data, significantly improving its accuracy on documents similar to those used for training.
11
+
12
+ ## Why Fine-tune?
13
+
14
+ - **Higher Accuracy:** Achieve better text extraction results on your specific document types.
15
+ - **Adaptability:** Train the model to recognize domain-specific terms, symbols, or layouts.
16
+ - **Reduced Errors:** Minimize downstream errors in data extraction and processing pipelines.
17
+
18
+ ## Strategy: Detect + LLM Correct + Export
19
+
20
+ Training an OCR model requires accurate ground truth: images of text snippets paired with their correct transcriptions. Manually creating this data is tedious. A powerful alternative leverages the strengths of different models:
21
+
22
+ 1. **Detect Text Regions:** Use a robust local OCR engine (like Surya or PaddleOCR) primarily for its *detection* capabilities (`detect_only=True`). This identifies the *locations* of text on the page, even if the initial *recognition* isn't perfect. You can combine this with layout analysis or region selections (`.region()`, `.below()`, `.add_exclusion()`) to focus on the specific areas you care about.
23
+ 2. **Correct with LLM:** For each detected text region, send the image snippet to a powerful Large Language Model (LLM) with multimodal capabilities (like GPT-4o, Claude 3.5 Sonnet/Haiku) using the `direct_ocr_llm` utility. The LLM performs high-accuracy OCR on the snippet, providing a "ground truth" transcription.
24
+ 3. **Export for Fine-tuning:** Use the `PaddleOCRRecognitionExporter` to package the original image snippets (from step 1) along with their corresponding LLM-generated text labels (from step 2) into the specific format required by PaddleOCR for fine-tuning its *recognition* model.
25
+
26
+ This approach combines the efficient spatial detection of local models with the superior text recognition of large generative models to create a high-quality fine-tuning dataset with minimal manual effort.
27
+
28
+ ## Example: Fine-tuning for Greek Spreadsheet Text
29
+
30
+ Let's walk through an example of preparing data to fine-tune PaddleOCR for text from a scanned Greek spreadsheet, adapting the process described above.
31
+
32
+ ```python
33
+ # --- 1. Setup and Load PDF ---
34
+ from natural_pdf import PDF
35
+ from natural_pdf.ocr.utils import direct_ocr_llm
36
+ from natural_pdf.exporters import PaddleOCRRecognitionExporter
37
+ import openai # Or your preferred LLM client library
38
+ import os
39
+
40
+ # Ensure your LLM API key is set (using environment variables is recommended)
41
+ # os.environ["OPENAI_API_KEY"] = "sk-..."
42
+ # os.environ["ANTHROPIC_API_KEY"] = "sk-..."
43
+
44
+ # pdf_path = "path/to/your/document.pdf"
45
+ pdf_path = "pdfs/hidden/the-bad-one.pdf" # Replace with your PDF path
46
+ pdf = PDF(pdf_path)
47
+
48
+ # --- 2. (Optional) Exclude Irrelevant Areas ---
49
+ # If the document has consistent headers, footers, or margins you want to ignore
50
+ # Use exclusions *before* detection
51
+ pdf.add_exclusion(lambda page: page.region(right=45)) # Exclude left margin/line numbers
52
+ pdf.add_exclusion(lambda page: page.region(left=500)) # Exclude right margin
53
+
54
+ # --- 3. Detect Text Regions ---
55
+ # Use a good detection engine. Surya is often robust for line detection.
56
+ # We only want the bounding boxes, not the initial (potentially inaccurate) OCR text.
57
+ print("Detecting text regions...")
58
+ # Process only a subset of pages for demonstration if needed
59
+ for page in pdf.pages[:10]:
60
+ # Use a moderate resolution for detection; higher res used for LLM correction later
61
+ page.apply_ocr(engine='surya', resolution=120, detect_only=True)
62
+ print(f"Detection complete for {num_pages_to_process} pages.")
63
+
64
+ # (Optional) Visualize detected boxes on a sample page
65
+ # pdf.pages[9].find_all('text[source=ocr]').show()
66
+
67
+ # --- 4. Correct with LLM ---
68
+ # Configure your LLM client (example using OpenAI client, adaptable for others)
69
+ # For Anthropic: client = openai.OpenAI(base_url="https://api.anthropic.com/v1/", api_key=os.environ.get("ANTHROPIC_API_KEY"))
70
+ client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
71
+
72
+ # Craft a clear prompt for the LLM
73
+ # Be as specific as possible! If it's in a specific language, what kinds
74
+ # of characters, etc.
75
+ prompt = """OCR this image patch. Return only the exact text content visible in the image.
76
+ Preserve original spelling, capitalization, punctuation, and symbols.
77
+ Do not add any explanatory text, translations, comments, or quotation marks around the result.
78
+ The text is likely from a Greek document, potentially a spreadsheet, containing Modern Greek words or numbers."""
79
+
80
+ # Define the correction function using direct_ocr_llm
81
+ def correct_text_region(region):
82
+ # Use a high resolution for the LLM call for best accuracy
83
+ return direct_ocr_llm(
84
+ region,
85
+ client,
86
+ prompt=prompt,
87
+ resolution=300,
88
+ # model="claude-3-5-sonnet-20240620" # Example Anthropic model
89
+ model="gpt-4o-mini" # Example OpenAI model
90
+ )
91
+
92
+ # Apply the correction function to the detected text regions
93
+ print("Applying LLM correction to detected regions...")
94
+ for page in pdf.pages[:num_pages_to_process]:
95
+ # This finds elements added by apply_ocr and passes their regions to 'correct_text_region'
96
+ # The returned text from the LLM replaces the original OCR text for these elements
97
+ # The source attribute is updated (e.g., to 'ocr-llm-corrected')
98
+ page.correct_ocr(correct_text_region)
99
+ print("LLM correction complete.")
100
+
101
+ # --- 5. Export for PaddleOCR Fine-tuning ---
102
+ print("Configuring exporter...")
103
+ exporter = PaddleOCRRecognitionExporter(
104
+ # Select all of the non-blank OCR text
105
+ # Hopefully it's all been LLM-corrected!
106
+ selector="text[source^=ocr][text!='']",
107
+ resolution=300, # Resolution for the exported image crops
108
+ padding=2, # Add slight padding around text boxes
109
+ split_ratio=0.9, # 90% for training, 10% for validation
110
+ random_seed=42, # For reproducible train/val split
111
+ include_guide=True # Include the Colab fine-tuning notebook
112
+ )
113
+
114
+ # Define the output directory
115
+ output_directory = "./my_paddleocr_finetune_data"
116
+ print(f"Exporting data to {output_directory}...")
117
+
118
+ # Run the export process
119
+ exporter.export(pdf, output_directory)
120
+
121
+ print("Export complete.")
122
+ print(f"Dataset ready for fine-tuning in: {output_directory}")
123
+ print(f"Next step: Upload '{os.path.join(output_directory, 'fine_tune_paddleocr.ipynb')}' and the rest of the contents to Google Colab.")
124
+
125
+ # --- Cleanup ---
126
+ pdf.close()
127
+ ```
128
+
129
+ ## Running the Fine-tuning
130
+
131
+ The `PaddleOCRRecognitionExporter` automatically includes a Jupyter Notebook (`fine_tune_paddleocr.ipynb`) in the output directory. This notebook is pre-configured to guide you through the fine-tuning process on Google Colab (which offers free GPU access):
132
+
133
+ 1. **Upload:** Upload the entire output directory (e.g., `my_paddleocr_finetune_data`) to your Google Drive or directly to your Colab instance.
134
+ 2. **Open Notebook:** Open the `fine_tune_paddleocr.ipynb` notebook in Google Colab.
135
+ 3. **Set Runtime:** Ensure the Colab runtime is set to use a GPU (Runtime -> Change runtime type -> GPU).
136
+ 4. **Run Cells:** Execute the cells in the notebook sequentially. It will:
137
+ * Install necessary libraries (PaddlePaddle, PaddleOCR).
138
+ * Point the training configuration to your uploaded dataset (`images/`, `train.txt`, `val.txt`, `dict.txt`).
139
+ * Download a pre-trained PaddleOCR model (usually a multilingual one).
140
+ * Start the fine-tuning process using your data.
141
+ * Save the fine-tuned model checkpoints.
142
+ * Export the best model into an "inference format" suitable for use with `natural-pdf`.
143
+ 5. **Download Model:** Download the resulting `inference_model` directory from Colab.
144
+
145
+ ## Using the Fine-tuned Model
146
+
147
+ Once you have the `inference_model` directory, you can instruct `natural-pdf` to use it for OCR:
148
+
149
+ ```python
150
+ from natural_pdf import PDF
151
+ from natural_pdf.ocr import PaddleOCROptions
152
+
153
+ # Path to the directory you downloaded from Colab
154
+ finetuned_model_dir = "/path/to/your/downloaded/inference_model"
155
+
156
+ # Specify the path in PaddleOCROptions
157
+ paddle_opts = PaddleOCROptions(
158
+ rec_model_dir=finetuned_model_dir,
159
+ rec_char_dict_path=os.path.join(finetuned_model_dir, 'your_dict.txt') # Or wherever your dict is
160
+ use_gpu=True # If using GPU locally
161
+ )
162
+
163
+ pdf = PDF("another-similar-document.pdf")
164
+ page = pdf.pages[0]
165
+
166
+ # Apply OCR using your fine-tuned model
167
+ ocr_elements = page.apply_ocr(engine='paddle', options=paddle_opts)
168
+
169
+ # Extract text using the improved results
170
+ text = page.extract_text()
171
+ print(text)
172
+
173
+ pdf.close()
174
+ ```
175
+
176
+ By following this process, you can significantly enhance OCR performance on your specific documents using the power of fine-tuning.
docs/index.md CHANGED
@@ -132,6 +132,25 @@ if result.get("found", False):
132
132
 
133
133
  [Learn about Document QA →](document-qa/index.ipynb)
134
134
 
135
+ ### Classify Pages and Regions
136
+
137
+ Categorize pages or specific regions based on their content using text or vision models.
138
+
139
+ **Note:** Requires `pip install "natural-pdf[classification]"`
140
+
141
+ ```python
142
+ # Classify a page based on text
143
+ categories = ["invoice", "scientific article", "presentation"]
144
+ page.classify(categories=categories, model="text")
145
+ print(f"Page Category: {page.category} (Confidence: {page.category_confidence:.2f})")
146
+
147
+
148
+ # Classify a page based on what it looks like
149
+ categories = ["invoice", "scientific article", "presentation"]
150
+ page.classify(categories=categories, model="vision")
151
+ print(f"Page Category: {page.category} (Confidence: {page.category_confidence:.2f})")
152
+ ```
153
+
135
154
  ### Visualize Your Work
136
155
 
137
156
  Debug and understand your extractions visually.
docs/ocr/index.md CHANGED
@@ -6,16 +6,16 @@ Natural PDF includes OCR (Optical Character Recognition) to extract text from sc
6
6
 
7
7
  Natural PDF supports multiple OCR engines:
8
8
 
9
- | Feature | EasyOCR | PaddleOCR | Surya OCR |
10
- |----------------------|------------------------------------|------------------------------------------|---------------------------------------|
11
- | **Installation** | `natural-pdf[easyocr]` | `natural-pdf[paddle]` | `natural-pdf[surya]` |
12
- | **Primary Strength** | Good general performance, simpler | Excellent Asian language, speed | High accuracy, multilingual lines |
13
- | **Speed** | Moderate | Fast | Moderate (GPU recommended) |
14
- | **Memory Usage** | Higher | Efficient | Higher (GPU recommended) |
15
- | **Paragraph Detect** | Yes (via option) | No | No (focuses on lines) |
16
- | **Handwritten** | Better support | Limited | Limited |
17
- | **Small Text** | Moderate | Good | Good |
18
- | **When to Use** | General documents, handwritten text| Asian languages, speed-critical tasks | Highest accuracy needed, line-level |
9
+ | Feature | EasyOCR | PaddleOCR | Surya OCR | Gemini (Layout + potential OCR) |
10
+ |----------------------|------------------------------------|------------------------------------------|---------------------------------------|--------------------------------------|
11
+ | **Installation** | `natural-pdf[easyocr]` | `natural-pdf[paddle]` | `natural-pdf[surya]` | `natural-pdf[gemini]` |
12
+ | **Primary Strength** | Good general performance, simpler | Excellent Asian language, speed | High accuracy, multilingual lines | Advanced layout analysis (via API) |
13
+ | **Speed** | Moderate | Fast | Moderate (GPU recommended) | API Latency |
14
+ | **Memory Usage** | Higher | Efficient | Higher (GPU recommended) | N/A (API) |
15
+ | **Paragraph Detect** | Yes (via option) | No | No (focuses on lines) | Yes (Layout model) |
16
+ | **Handwritten** | Better support | Limited | Limited | Potentially (API model dependent) |
17
+ | **Small Text** | Moderate | Good | Good | Potentially (API model dependent) |
18
+ | **When to Use** | General documents, handwritten text| Asian languages, speed-critical tasks | Highest accuracy needed, line-level | Complex layouts, API integration |
19
19
 
20
20
  ## Basic OCR Usage
21
21
 
@@ -53,6 +53,7 @@ For advanced, engine-specific settings, use the Options classes:
53
53
 
54
54
  ```python
55
55
  from natural_pdf.ocr import PaddleOCROptions, EasyOCROptions, SuryaOCROptions
56
+ from natural_pdf.analyzers.layout import GeminiOptions # Note: Gemini is primarily layout
56
57
 
57
58
  # --- Configure PaddleOCR ---
58
59
  paddle_opts = PaddleOCROptions(
@@ -90,6 +91,25 @@ surya_opts = SuryaOCROptions(
90
91
  # set via environment variables (see note below).
91
92
  )
92
93
  ocr_elements = page.apply_ocr(engine='surya', options=surya_opts)
94
+
95
+ # --- Configure Gemini (as layout analyzer, can be used with OCR) ---
96
+ # Gemini requires API key (GOOGLE_API_KEY environment variable)
97
+ # Note: Gemini is used via apply_layout, but its options can influence OCR if used together
98
+ gemini_opts = GeminiOptions(
99
+ prompt="Extract text content and identify document elements.",
100
+ # model_name="gemini-1.5-flash-latest" # Specify a model if needed
101
+ # See GeminiOptions documentation for more parameters
102
+ )
103
+ # Typically used like this (layout first, then potentially OCR on regions)
104
+ layout_elements = page.apply_layout(engine='gemini', options=gemini_opts)
105
+ # If Gemini also performed OCR or you want to OCR layout regions:
106
+ # ocr_elements = some_region.apply_ocr(...)
107
+
108
+ # It can sometimes be used directly if the model supports it, but less common:
109
+ # try:
110
+ # ocr_elements = page.apply_ocr(engine='gemini', options=gemini_opts)
111
+ # except Exception as e:
112
+ # print(f"Gemini might not be configured for direct OCR via apply_ocr: {e}")
93
113
  ```
94
114
 
95
115
  ## Applying OCR Directly
@@ -105,6 +125,9 @@ print(f"Found {len(ocr_elements)} text elements via OCR")
105
125
  title = page.find('text:contains("Title")')
106
126
  content_region = title.below(height=300)
107
127
  region_ocr_elements = content_region.apply_ocr(engine='paddle', languages=['en'])
128
+
129
+ # Note: Re-applying OCR to the same page or region will remove any
130
+ # previously generated OCR elements for that area before adding the new ones.
108
131
  ```
109
132
 
110
133
  ## OCR Engines
@@ -190,15 +213,39 @@ page.correct_ocr(correct)
190
213
  # You're done!
191
214
  ```
192
215
 
193
- ## Debugging OCR
216
+ ## Interactive OCR Correction / Debugging
194
217
 
195
- ```python
196
- from natural_pdf.utils.packaging import create_correction_task_package
218
+ Natural PDF includes a utility to package a PDF and its detected elements, along with an interactive web application (SPA) for reviewing and correcting OCR results.
197
219
 
198
- create_correction_task_package(pdf, "original.zip", overwrite=True)
199
- ```
220
+ 1. **Package the data:**
221
+ Use the `create_correction_task_package` function to create a zip file containing the necessary data for the SPA.
222
+
223
+ ```python
224
+ from natural_pdf.utils.packaging import create_correction_task_package
225
+
226
+ # Assuming 'pdf' is your loaded PDF object after running apply_ocr or apply_layout
227
+ create_correction_task_package(pdf, "correction_package.zip", overwrite=True)
228
+ ```
229
+
230
+ 2. **Run the SPA:**
231
+ The correction SPA is bundled with the library. You need to run a simple web server from the directory containing the SPA's files. The location of these files might depend on your installation, but you can typically find them within the installed `natural_pdf` package directory under `templates/spa`.
232
+
233
+ *Example using Python's built-in server (run from your terminal):*
234
+
235
+ ```bash
236
+ # Find the path to the installed natural_pdf package
237
+ # (This command might vary depending on your environment)
238
+ NATURAL_PDF_PATH=$(python -c "import site; print(site.getsitepackages()[0])")/natural_pdf
239
+
240
+ # Navigate to the SPA directory
241
+ cd $NATURAL_PDF_PATH/templates/spa
242
+
243
+ # Start the web server (e.g., on port 8000)
244
+ python -m http.server 8000
245
+ ```
200
246
 
201
- This will at *some point* be official-ized, but for now you can look at `templates/spa` and see the correction package.
247
+ 3. **Use the SPA:**
248
+ Open your web browser to `http://localhost:8000`. The SPA should load, allowing you to drag and drop the `correction_package.zip` file you created into the application to view and edit the OCR results.
202
249
 
203
250
  ## Next Steps
204
251