kreuzberg 1.0.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Na'aman Hirschfeld
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,259 @@
1
+ Metadata-Version: 2.2
2
+ Name: kreuzberg
3
+ Version: 1.0.0
4
+ Summary: A text extraction library supporting PDFs, images, office documents and more
5
+ Author-email: Na'aman Hirschfeld <nhirschfed@gmail.com>
6
+ License: MIT
7
+ Project-URL: homepage, https://github.com/Goldziher/kreuzberg
8
+ Keywords: async,document-processing,docx,image-to-text,latex,markdown,ocr,odt,office-documents,pandoc,pdf,pdf-extraction,rag,tesseract,text-extraction,text-processing
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: General
21
+ Classifier: Topic :: Utilities
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: anyio>=4.8.0
27
+ Requires-Dist: charset-normalizer>=3.4.1
28
+ Requires-Dist: pypandoc>=1.15
29
+ Requires-Dist: pypdfium2>=4.30.1
30
+ Requires-Dist: pytesseract>=0.3.13
31
+ Requires-Dist: typing-extensions>=4.12.2
32
+
33
+ # Kreuzberg
34
+
35
+ Kreuzberg is a library for simplified text extraction from PDF files. It's meant to offer simple, hassle free text
36
+ extraction.
37
+
38
+ Why?
39
+
40
+ I am building, like many do now, a RAG focused service. I have text extraction needs.
41
+ There are quite a lot of commercial options out there, and several open-source + paid options.
42
+ But I wanted something simple, which does not require expansive round-trips to an external API.
43
+ Furthermore, I wanted something that is easy to run locally and isn't very heavy / requires a GPU.
44
+
45
+ Hence, this library.
46
+
47
+ ## Features
48
+
49
+ - Extract text from PDFs, images, and office documents
50
+ - Use modern Python with async (via `anyio`) and proper type hints
51
+ - Extensive error handling for easy debugging
52
+
53
+ ## Installation
54
+
55
+ 1. Begin by installing the python package:
56
+
57
+ ```shell
58
+
59
+ pip install kreuzberg
60
+
61
+ ```
62
+
63
+ 2. Install the system dependencies:
64
+
65
+ - [pandoc](https://pandoc.org/installing.html) (non-pdf text extraction, GPL v2.0 licensed but used via CLI only)
66
+ - [tesseract-ocr](https://tesseract-ocr.github.io/) (for image/PDF OCR, Apache License)
67
+
68
+ ## Supported File Types
69
+
70
+ Kreuzberg supports a wide range of file formats:
71
+
72
+ ### Document Formats
73
+
74
+ - PDF (`.pdf`) - both searchable and scanned documents
75
+ - Word Documents (`.docx`)
76
+ - OpenDocument Text (`.odt`)
77
+ - Rich Text Format (`.rtf`)
78
+
79
+ ### Image Formats
80
+
81
+ - JPEG, JPG (`.jpg`, `.jpeg`, `.pjpeg`)
82
+ - PNG (`.png`)
83
+ - TIFF (`.tiff`, `.tif`)
84
+ - BMP (`.bmp`)
85
+ - GIF (`.gif`)
86
+ - WebP (`.webp`)
87
+ - JPEG 2000 (`.jp2`, `.jpx`, `.jpm`, `.mj2`)
88
+ - Portable Anymap (`.pnm`)
89
+ - Portable Bitmap (`.pbm`)
90
+ - Portable Graymap (`.pgm`)
91
+ - Portable Pixmap (`.ppm`)
92
+
93
+ #### Text and Markup Formats
94
+
95
+ - Plain Text (`.txt`)
96
+ - Markdown (`.md`)
97
+ - reStructuredText (`.rst`)
98
+ - LaTeX (`.tex`)
99
+
100
+ #### Data Formats
101
+
102
+ - Comma-Separated Values (`.csv`)
103
+ - Tab-Separated Values (`.tsv`)
104
+
105
+ All formats support text extraction, with different processing methods:
106
+
107
+ - PDFs are processed using pdfium2 for searchable PDFs and Tesseract OCR for scanned documents
108
+ - Images are processed using Tesseract OCR
109
+ - Office documents and other formats are processed using Pandoc
110
+ - Plain text files are read directly with appropriate encoding detection
111
+
112
+ ## Usage
113
+
114
+ Kreuzberg exports two async functions:
115
+
116
+ - Extract text from a file (string path or `pathlib.Path`) using `extract_file()`
117
+ - Extract text from a byte-string using `extract_bytes()`
118
+
119
+ Note - both of these functions are async and therefore should be used in an async context.
120
+
121
+ ### Extract from File
122
+
123
+ ```python
124
+ from pathlib import Path
125
+ from kreuzberg import extract_file
126
+
127
+
128
+ # Extract text from a PDF file
129
+ async def extract_pdf():
130
+ result = await extract_file("document.pdf")
131
+ print(f"Extracted text: {result.content}")
132
+ print(f"Output mime type: {result.mime_type}")
133
+
134
+
135
+ # Extract text from an image
136
+ async def extract_image():
137
+ result = await extract_file("scan.png")
138
+ print(f"Extracted text: {result.content}")
139
+
140
+
141
+ # or use Path
142
+
143
+ async def extract_pdf():
144
+ result = await extract_file(Path("document.pdf"))
145
+ print(f"Extracted text: {result.content}")
146
+ print(f"Output mime type: {result.mime_type}")
147
+ ```
148
+
149
+ ### Extract from Bytes
150
+
151
+ ```python
152
+ from kreuzberg import extract_bytes
153
+
154
+
155
+ # Extract text from PDF bytes
156
+ async def process_uploaded_pdf(pdf_content: bytes):
157
+ result = await extract_bytes(pdf_content, mime_type="application/pdf")
158
+ return result.content
159
+
160
+
161
+ # Extract text from image bytes
162
+ async def process_uploaded_image(image_content: bytes):
163
+ result = await extract_bytes(image_content, mime_type="image/jpeg")
164
+ return result.content
165
+ ```
166
+
167
+ ### Error Handling
168
+
169
+ Kreuzberg raises two exception types:
170
+
171
+ #### ValidationError
172
+
173
+ Raised when there are issues with input validation:
174
+
175
+ - Unsupported mime types
176
+ - Non-existent files
177
+ - Undetectable mime types
178
+
179
+ #### ParsingError
180
+
181
+ Raised when there are issues during the text extraction process:
182
+
183
+ - PDF parsing failures
184
+ - OCR errors
185
+ - Pandoc conversion errors
186
+
187
+ ```python
188
+ from kreuzberg import extract_file
189
+ from kreuzberg.exceptions import ValidationError, ParsingError
190
+
191
+
192
+ async def safe_extract():
193
+ try:
194
+ result = await extract_file("document.doc")
195
+ return result.content
196
+ except ValidationError as e:
197
+ print(f"Validation error: {e.message}")
198
+ print(f"Context: {e.context}")
199
+ except ParsingError as e:
200
+ print(f"Parsing error: {e.message}")
201
+ print(f"Context: {e.context}") # Contains detailed error information
202
+ ```
203
+
204
+ Both error types include helpful context information for debugging:
205
+
206
+ ```python
207
+ try:
208
+ result = await extract_file("scanned.pdf")
209
+ except ParsingError as e:
210
+ # e.context might contain:
211
+ # {
212
+ # "file_path": "scanned.pdf",
213
+ # "error": "Tesseract OCR failed: Unable to process image"
214
+ # }
215
+ ```
216
+
217
+ ### ExtractionResult
218
+
219
+ All extraction functions return an ExtractionResult named tuple containing:
220
+
221
+ - content: The extracted text as a string
222
+ - mime_type: The mime type of the output (either "text/plain" or, if pandoc is used- "text/markdown")
223
+
224
+ ```python
225
+ from kreuzberg import ExtractionResult
226
+
227
+
228
+ async def process_document(path: str) -> str:
229
+ result: ExtractionResult = await extract_file(path)
230
+ return result.content
231
+
232
+
233
+ # or access the result as tuple
234
+
235
+ async def process_document(path: str) -> str:
236
+ content, mime_type = await extract_file(path)
237
+ # do something with mime_type
238
+ return content
239
+ ```
240
+
241
+ ## Contribution
242
+
243
+ This library is open to contribution. Feel free to open issues or submit PRs. Its better to discuss issues before
244
+ submitting PRs to avoid disappointment.
245
+
246
+ ### Local Development
247
+
248
+ 1. Clone the repo
249
+ 2. Install the system dependencies
250
+ 3. Install the full dependencies with `uv sync`
251
+ 4. Install the pre-commit hooks with:
252
+ ```shell
253
+ pre-commit install && pre-commit install --hook-type commit-msg
254
+ ```
255
+ 5. Make your changes and submit a PR
256
+
257
+ ## License
258
+
259
+ This library uses the MIT license.
@@ -0,0 +1,227 @@
1
+ # Kreuzberg
2
+
3
+ Kreuzberg is a library for simplified text extraction from PDF files. It's meant to offer simple, hassle free text
4
+ extraction.
5
+
6
+ Why?
7
+
8
+ I am building, like many do now, a RAG focused service. I have text extraction needs.
9
+ There are quite a lot of commercial options out there, and several open-source + paid options.
10
+ But I wanted something simple, which does not require expansive round-trips to an external API.
11
+ Furthermore, I wanted something that is easy to run locally and isn't very heavy / requires a GPU.
12
+
13
+ Hence, this library.
14
+
15
+ ## Features
16
+
17
+ - Extract text from PDFs, images, and office documents
18
+ - Use modern Python with async (via `anyio`) and proper type hints
19
+ - Extensive error handling for easy debugging
20
+
21
+ ## Installation
22
+
23
+ 1. Begin by installing the python package:
24
+
25
+ ```shell
26
+
27
+ pip install kreuzberg
28
+
29
+ ```
30
+
31
+ 2. Install the system dependencies:
32
+
33
+ - [pandoc](https://pandoc.org/installing.html) (non-pdf text extraction, GPL v2.0 licensed but used via CLI only)
34
+ - [tesseract-ocr](https://tesseract-ocr.github.io/) (for image/PDF OCR, Apache License)
35
+
36
+ ## Supported File Types
37
+
38
+ Kreuzberg supports a wide range of file formats:
39
+
40
+ ### Document Formats
41
+
42
+ - PDF (`.pdf`) - both searchable and scanned documents
43
+ - Word Documents (`.docx`)
44
+ - OpenDocument Text (`.odt`)
45
+ - Rich Text Format (`.rtf`)
46
+
47
+ ### Image Formats
48
+
49
+ - JPEG, JPG (`.jpg`, `.jpeg`, `.pjpeg`)
50
+ - PNG (`.png`)
51
+ - TIFF (`.tiff`, `.tif`)
52
+ - BMP (`.bmp`)
53
+ - GIF (`.gif`)
54
+ - WebP (`.webp`)
55
+ - JPEG 2000 (`.jp2`, `.jpx`, `.jpm`, `.mj2`)
56
+ - Portable Anymap (`.pnm`)
57
+ - Portable Bitmap (`.pbm`)
58
+ - Portable Graymap (`.pgm`)
59
+ - Portable Pixmap (`.ppm`)
60
+
61
+ #### Text and Markup Formats
62
+
63
+ - Plain Text (`.txt`)
64
+ - Markdown (`.md`)
65
+ - reStructuredText (`.rst`)
66
+ - LaTeX (`.tex`)
67
+
68
+ #### Data Formats
69
+
70
+ - Comma-Separated Values (`.csv`)
71
+ - Tab-Separated Values (`.tsv`)
72
+
73
+ All formats support text extraction, with different processing methods:
74
+
75
+ - PDFs are processed using pdfium2 for searchable PDFs and Tesseract OCR for scanned documents
76
+ - Images are processed using Tesseract OCR
77
+ - Office documents and other formats are processed using Pandoc
78
+ - Plain text files are read directly with appropriate encoding detection
79
+
80
+ ## Usage
81
+
82
+ Kreuzberg exports two async functions:
83
+
84
+ - Extract text from a file (string path or `pathlib.Path`) using `extract_file()`
85
+ - Extract text from a byte-string using `extract_bytes()`
86
+
87
+ Note - both of these functions are async and therefore should be used in an async context.
88
+
89
+ ### Extract from File
90
+
91
+ ```python
92
+ from pathlib import Path
93
+ from kreuzberg import extract_file
94
+
95
+
96
+ # Extract text from a PDF file
97
+ async def extract_pdf():
98
+ result = await extract_file("document.pdf")
99
+ print(f"Extracted text: {result.content}")
100
+ print(f"Output mime type: {result.mime_type}")
101
+
102
+
103
+ # Extract text from an image
104
+ async def extract_image():
105
+ result = await extract_file("scan.png")
106
+ print(f"Extracted text: {result.content}")
107
+
108
+
109
+ # or use Path
110
+
111
+ async def extract_pdf():
112
+ result = await extract_file(Path("document.pdf"))
113
+ print(f"Extracted text: {result.content}")
114
+ print(f"Output mime type: {result.mime_type}")
115
+ ```
116
+
117
+ ### Extract from Bytes
118
+
119
+ ```python
120
+ from kreuzberg import extract_bytes
121
+
122
+
123
+ # Extract text from PDF bytes
124
+ async def process_uploaded_pdf(pdf_content: bytes):
125
+ result = await extract_bytes(pdf_content, mime_type="application/pdf")
126
+ return result.content
127
+
128
+
129
+ # Extract text from image bytes
130
+ async def process_uploaded_image(image_content: bytes):
131
+ result = await extract_bytes(image_content, mime_type="image/jpeg")
132
+ return result.content
133
+ ```
134
+
135
+ ### Error Handling
136
+
137
+ Kreuzberg raises two exception types:
138
+
139
+ #### ValidationError
140
+
141
+ Raised when there are issues with input validation:
142
+
143
+ - Unsupported mime types
144
+ - Non-existent files
145
+ - Undetectable mime types
146
+
147
+ #### ParsingError
148
+
149
+ Raised when there are issues during the text extraction process:
150
+
151
+ - PDF parsing failures
152
+ - OCR errors
153
+ - Pandoc conversion errors
154
+
155
+ ```python
156
+ from kreuzberg import extract_file
157
+ from kreuzberg.exceptions import ValidationError, ParsingError
158
+
159
+
160
+ async def safe_extract():
161
+ try:
162
+ result = await extract_file("document.doc")
163
+ return result.content
164
+ except ValidationError as e:
165
+ print(f"Validation error: {e.message}")
166
+ print(f"Context: {e.context}")
167
+ except ParsingError as e:
168
+ print(f"Parsing error: {e.message}")
169
+ print(f"Context: {e.context}") # Contains detailed error information
170
+ ```
171
+
172
+ Both error types include helpful context information for debugging:
173
+
174
+ ```python
175
+ try:
176
+ result = await extract_file("scanned.pdf")
177
+ except ParsingError as e:
178
+ # e.context might contain:
179
+ # {
180
+ # "file_path": "scanned.pdf",
181
+ # "error": "Tesseract OCR failed: Unable to process image"
182
+ # }
183
+ ```
184
+
185
+ ### ExtractionResult
186
+
187
+ All extraction functions return an ExtractionResult named tuple containing:
188
+
189
+ - content: The extracted text as a string
190
+ - mime_type: The mime type of the output (either "text/plain" or, if pandoc is used- "text/markdown")
191
+
192
+ ```python
193
+ from kreuzberg import ExtractionResult
194
+
195
+
196
+ async def process_document(path: str) -> str:
197
+ result: ExtractionResult = await extract_file(path)
198
+ return result.content
199
+
200
+
201
+ # or access the result as tuple
202
+
203
+ async def process_document(path: str) -> str:
204
+ content, mime_type = await extract_file(path)
205
+ # do something with mime_type
206
+ return content
207
+ ```
208
+
209
+ ## Contribution
210
+
211
+ This library is open to contribution. Feel free to open issues or submit PRs. Its better to discuss issues before
212
+ submitting PRs to avoid disappointment.
213
+
214
+ ### Local Development
215
+
216
+ 1. Clone the repo
217
+ 2. Install the system dependencies
218
+ 3. Install the full dependencies with `uv sync`
219
+ 4. Install the pre-commit hooks with:
220
+ ```shell
221
+ pre-commit install && pre-commit install --hook-type commit-msg
222
+ ```
223
+ 5. Make your changes and submit a PR
224
+
225
+ ## License
226
+
227
+ This library uses the MIT license.
@@ -0,0 +1,11 @@
1
+ from .exceptions import KreuzbergError, ParsingError, ValidationError
2
+ from .extraction import ExtractionResult, extract_bytes, extract_file
3
+
4
+ __all__ = [
5
+ "ExtractionResult",
6
+ "KreuzbergError",
7
+ "ParsingError",
8
+ "ValidationError",
9
+ "extract_bytes",
10
+ "extract_file",
11
+ ]
@@ -0,0 +1,145 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, cast
4
+
5
+ from charset_normalizer import detect
6
+ from pypandoc import convert_file, convert_text
7
+ from pypdfium2 import PdfDocument, PdfiumError
8
+ from pytesseract import TesseractError, image_to_string
9
+
10
+ from kreuzberg._mime_types import PANDOC_MIME_TYPE_EXT_MAP
11
+ from kreuzberg._sync import run_sync
12
+ from kreuzberg.exceptions import ParsingError
13
+
14
+ if TYPE_CHECKING:
15
+ from pathlib import Path
16
+
17
+
18
+ def _extract_pdf_with_tesseract(file_path: Path) -> str:
19
+ """Extract text from a scanned PDF file using pytesseract.
20
+
21
+ Args:
22
+ file_path: The path to the PDF file.
23
+
24
+ Raises:
25
+ ParsingError: If the text could not be extracted from the PDF file.
26
+
27
+ Returns:
28
+ The extracted text.
29
+ """
30
+ try:
31
+ # make it into an image here:
32
+ pdf = PdfDocument(str(file_path))
33
+ images = [page.render(scale=2.0).to_pil() for page in pdf]
34
+
35
+ text = "\n".join(image_to_string(img) for img in images)
36
+ return text.strip()
37
+ except (PdfiumError, TesseractError) as e:
38
+ raise ParsingError(
39
+ "Could not extract text from PDF file", context={"file_path": str(file_path), "error": str(e)}
40
+ ) from e
41
+
42
+
43
+ def _extract_pdf_with_pdfium2(file_path: Path) -> str:
44
+ """Extract text from a searchable PDF file using pypdfium2.
45
+
46
+ Args:
47
+ file_path: The path to the PDF file.
48
+
49
+ Raises:
50
+ ParsingError: If the text could not be extracted from the PDF file.
51
+
52
+ Returns:
53
+ The extracted text.
54
+ """
55
+ try:
56
+ document = PdfDocument(file_path)
57
+ text = "\n".join(page.get_textpage().get_text_range() for page in document)
58
+ return text.strip()
59
+ except PdfiumError as e:
60
+ raise ParsingError(
61
+ "Could not extract text from PDF file", context={"file_path": str(file_path), "error": str(e)}
62
+ ) from e
63
+
64
+
65
+ async def _extract_pdf_file(file_path: Path) -> str:
66
+ """Extract text from a PDF file.
67
+
68
+ Args:
69
+ file_path: The path to the PDF file.
70
+
71
+ Returns:
72
+ The extracted text.
73
+ """
74
+ if content := await run_sync(_extract_pdf_with_pdfium2, file_path):
75
+ return content
76
+
77
+ return await run_sync(_extract_pdf_with_tesseract, file_path)
78
+
79
+
80
+ async def _extract_content_with_pandoc(file_data: bytes, mime_type: str, encoding: str | None = None) -> str:
81
+ """Extract text using pandoc.
82
+
83
+ Args:
84
+ file_data: The content of the file.
85
+ mime_type: The mime type of the file.
86
+ encoding: An optional encoding to use when decoding the string.
87
+
88
+ Raises:
89
+ ParsingError: If the text could not be extracted from the file using pandoc.
90
+
91
+ Returns:
92
+ The extracted text.
93
+ """
94
+ ext = PANDOC_MIME_TYPE_EXT_MAP[mime_type]
95
+ encoding = encoding or detect(file_data)["encoding"] or "utf-8"
96
+ try:
97
+ return cast(str, await run_sync(convert_text, file_data, to="md", format=ext, encoding=encoding))
98
+ except RuntimeError as e:
99
+ raise ParsingError(
100
+ f"Could not extract text from {PANDOC_MIME_TYPE_EXT_MAP[mime_type]} file contents",
101
+ context={"error": str(e)},
102
+ ) from e
103
+
104
+
105
+ async def _extract_file_with_pandoc(file_path: Path | str, mime_type: str) -> str:
106
+ """Extract text using pandoc.
107
+
108
+ Args:
109
+ file_path: The path to the file.
110
+ mime_type: The mime type of the file.
111
+
112
+ Raises:
113
+ ParsingError: If the text could not be extracted from the file using pandoc.
114
+
115
+ Returns:
116
+ The extracted text.
117
+ """
118
+ ext = PANDOC_MIME_TYPE_EXT_MAP[mime_type]
119
+ try:
120
+ return cast(str, await run_sync(convert_file, file_path, to="md", format=ext))
121
+ except RuntimeError as e:
122
+ raise ParsingError(
123
+ f"Could not extract text from {PANDOC_MIME_TYPE_EXT_MAP[mime_type]} file",
124
+ context={"file_path": str(file_path), "error": str(e)},
125
+ ) from e
126
+
127
+
128
+ async def _extract_image_with_tesseract(file_path: Path | str) -> str:
129
+ """Extract text from an image file.
130
+
131
+ Args:
132
+ file_path: The path to the image file.
133
+
134
+ Raises:
135
+ ParsingError: If the text could not be extracted from the image file.
136
+
137
+ Returns:
138
+ The extracted content.
139
+ """
140
+ try:
141
+ return cast(str, image_to_string(str(file_path)).strip())
142
+ except TesseractError as e:
143
+ raise ParsingError(
144
+ "Could not extract text from image file", context={"file_path": str(file_path), "error": str(e)}
145
+ ) from e