同步完整源码 - 2026-05-24

This commit is contained in:
xiaoxue
2026-05-24 23:41:32 +08:00
commit 755d34b16a
46 changed files with 2622 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
name: build
on:
schedule:
- cron: '5 0 * * *'
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.13", "3.12", "3.11", "3.10", "3.9"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name : Build and run tests
run: |
mkdir $HOME/test_external_dir
cd $HOME/test_external_dir
cp $GITHUB_WORKSPACE/tests . -r
python -m venv venv
source venv/bin/activate
pip install $GITHUB_WORKSPACE pytest pytest-xdist
python -m pytest -n=auto
+52
View File
@@ -0,0 +1,52 @@
name: PyPI
on:
release:
types: [published]
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: deploy
url: https://pypi.org/p/hotpdf
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python3 -m pip install --upgrade setuptools wheel twine build
- name: Build and publish
env:
TWINE_USERNAME: ${{secrets.TWINE_USERNAME}}
TWINE_PASSWORD: ${{secrets.TWINE_PASSWORD}}
run: |
python -m build
twine upload dist/*
badge:
needs: deploy
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.13", "3.12", "3.11", "3.10", "3.9"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name : Install from PyPI and run tests
run: |
sleep 2m
mkdir $HOME/test_external_dir
cd $HOME/test_external_dir
cp $GITHUB_WORKSPACE/tests/ . -r
python -m venv venv
source venv/bin/activate
pip install hotpdf pytest pytest-xdist
python -m pytest tests -n=auto
+72
View File
@@ -0,0 +1,72 @@
name: Unit tests
on:
push:
branches:
- main
pull_request:
workflow_dispatch:
jobs:
linter:
name: Linters
runs-on: ubuntu-latest
env:
Python3_ROOT_DIR:
timeout-minutes: 2
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Python 3.11
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Cache python packages
uses: actions/cache@v4
id: cache
with:
path: ${{ env.Python3_ROOT_DIR }}/lib/python3.11/site-packages
key: dev-${{ hashFiles('**/pyproject.toml') }}-3.11
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -e '.[dev]'
- name: Lint with ruff
run: |
pip install --upgrade --force-reinstall ruff
python3 -m ruff check
- name: Run mypy
run: python -m mypy
tests:
needs: linter
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
env:
Python3_ROOT_DIR:
name: Tests
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Cache python packages
uses: actions/cache@v4
id: cache
with:
path: ${{ env.Python3_ROOT_DIR }}/lib/python${{ matrix.python-version }}/site-packages
key: dev-${{ hashFiles('**/pyproject.toml') }}-${{ matrix.python-version }}
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -e '.[dev]'
- name: Run tests
run:
python -m pytest --cov-fail-under=96 -n=auto --cov=hotpdf --cov-report term-missing
- name: Upload coverage to coveralls
if: github.event_name == 'push'
uses: coverallsapp/github-action@v2.2.3
+171
View File
@@ -0,0 +1,171 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# ruff
.ruff_cache
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.vscode/
# MACOS
.DS_Store
# Project specific
main.py
memray-*
+24
View File
@@ -0,0 +1,24 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: local
hooks:
- id: ruff-lint
name: ruff lint
entry: ruff check
language: system
pass_filenames: false
- id: ruff-format
name: ruff format
entry: ruff format
language: system
pass_filenames: false
- id: mypy
name: mypy
entry: mypy
language: system
pass_filenames: false
+16
View File
@@ -0,0 +1,16 @@
version: 2
build:
os: "ubuntu-22.04"
tools:
python: "3.11"
sphinx:
configuration: docs/source/conf.py
python:
install:
- method: pip
path: .
extra_requirements:
- docs
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Prestatech GmbH
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+147
View File
@@ -0,0 +1,147 @@
# hotpdf
[![Documentation Status](https://readthedocs.org/projects/hotpdf/badge/?version=latest)](https://hotpdf.readthedocs.io/en/latest/?badge=latest)
[![latest](https://github.com/weareprestatech/hotpdf/actions/workflows/python-publish.yml/badge.svg)](https://github.com/weareprestatech/hotpdf/actions/workflows/python-publish.yml)
[![build](https://github.com/weareprestatech/hotpdf/actions/workflows/build-badge.yml/badge.svg)](https://github.com/weareprestatech/hotpdf/actions/workflows/build-badge.yml)
[![Coverage Status](https://coveralls.io/repos/github/weareprestatech/hotpdf/badge.svg?branch=main)](https://coveralls.io/github/weareprestatech/hotpdf?branch=main)
[![Unit tests](https://github.com/weareprestatech/hotpdf/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/weareprestatech/hotpdf/actions/workflows/test.yml)
This project was started as an internal project @ [Prestatech](http://prestatech.com/) to parse PDF files in a fast and memory-efficient way to overcome the difficulties we were having while parsing big PDF files using libraries such as [pdfquery](https://github.com/jcushman/pdfquery) [[Comparison](https://imgur.com/a/5XuwEqq)].
hotpdf is a wrapper around [pdfminer.six](https://github.com/pdfminer/pdfminer.six) focusing on text extraction and text search operations on PDFs.
hotpdf can be used to find and extract text from PDFs.
Please [read the docs](https://hotpdf.readthedocs.io/en/latest/) to understand how the library can help you!
## Installation
The latest version of hotpdf can be installed directly from [PyPI](https://pypi.org/project/hotpdf/) with pip.
```bash
pip install hotpdf
```
## Local Setup
First, install the dependencies required by hotpdf
```bash
python3 -m pip install -e .
```
### Contributing
You should install the [pre-commit](https://github.com/weareprestatech/hotpdf/blob/main/.pre-commit-config.yaml) hooks with `pre-commit install`. This will run the linter, mypy, and ruff formatting before each commit.
Remember to run `pip install -e '.[dev]'` to install the extra dependencies for development.
For more examples of how to run the full test suite please refer to the [CI workflow](https://github.com/weareprestatech/hotpdf/blob/main/.github/workflows/test.yml).
We strive to keep the test coverage at 100% (but can't due to certain reasons - e.g., test file not available): if you want your contributions accepted please write tests for them :D
Some examples of running tests locally:
```bash
python3 -m pip install -e '.[dev]' # install extra deps for testing
python3 -m pytest -n=auto tests/ # run the test suite
# run tests with coverage
python3 -m pytest --cov-fail-under=96 -n=auto --cov=hotpdf --cov-report term-missing
```
### Documentation
We use [sphinx](https://www.sphinx-doc.org/en/master/) for generating our docs and host them on [readthedocs](https://readthedocs.org/)
Please update and add documentation if required, with your contributions.
Update the `.rst` files, rebuild them, and commit them along with your PRs.
```bash
cd docs
make clean
make html
```
This will generate the necessary documentation files. Once merged to `main` the docs will be updated automatically.
## Usage
**To view more detailed usage information, please [read the docs](https://hotpdf.readthedocs.io/en/latest/)**
Basic usage is as follows:
```python
from hotpdf import HotPdf
pdf_file_path = "test.pdf"
# Load pdf file into memory
hotpdf_document = HotPdf(pdf_file_path)
# Alternatively, you can also pass an opened PDF stream to be loaded
with open(pdf_file_path, "rb") as f:
hotpdf_document_2 = HotPdf(f)
# You can also merge multiple HotPdf objects to get one single HotPdf object
merged_hotpdf_object = HotPdf.merge_multiple(hotpdfs=[hotpdf1, hotpdf2])
# Get the number of pages
print(len(hotpdf_document.pages))
# Find text
text_occurences = hotpdf_document.find_text("foo")
# Find text and its full span
text_occurences_full_span = hotpdf_document.find_text("foo", take_span=True)
# Extract text in the region
text_in_bbox = hotpdf_document.extract_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract spans in the region
spans_in_bbox = hotpdf_document.extract_spans(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract spans text in the region
spans_text_in_bbox = hotpdf_document.extract_spans_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract full-page text
full_page_text = hotpdf_document.extract_page_text(page=0)
```
## Known Issues
1. (cid:x) characters in text - In some pdfs when extracted, some symbols like `€` might not be properly decoded, and instead be extracted as `(cid:128)`.
This is a problem with the `pdfminer.six` library. We have fixed it from our side on our [fork](https://github.com/weareprestatech/pdfminer.six), and you can install it using pip. Until we can merge it to pdfminer.six repo and it gets released, we recommend that you install our fork with the fixes manually.
```bash
pip install --no-cache-dir git+https://github.com/weareprestatech/pdfminer.six.git@20240222#egg=pdfminer-six
```
## License
This project is licensed under the terms of the MIT license.
---
with ❤️ from the team @ [Prestatech GmbH](https://prestatech.com/)
+49
View File
@@ -0,0 +1,49 @@
from hotpdf import HotPdf
pdf_file_path = "test.pdf"
# Load pdf file into memory
hotpdf_document = HotPdf(pdf_file_path)
# Alternatively, you can also pass an opened pdf stream to be loaded
with open(pdf_file_path, "rb") as f:
hotpdf_document_2 = HotPdf(f)
# Get number of pages
print(len(hotpdf_document.pages))
# Find text
text_occurences = hotpdf_document.find_text("foo")
# Find text and its full span
text_occurences_full_span = hotpdf_document.find_text("foo", take_span=True)
# Extract text in region
text_in_bbox = hotpdf_document.extract_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract spans in region
spans_in_bbox = hotpdf_document.extract_spans(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract spans text in region
spans_text_in_bbox = hotpdf_document.extract_spans_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
# Extract full page text
full_page_text = hotpdf_document.extract_page_text(page=0)
+1
View File
@@ -0,0 +1 @@
* text=auto
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+35
View File
@@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
+17
View File
@@ -0,0 +1,17 @@
API
===
.. autosummary::
:toctree: generated
hotpdf.hotpdf.HotPdf
hotpdf.memory_map.MemoryMap
hotpdf.sparse_matrix.SparseMatrix
hotpdf.span_map.SpanMap
hotpdf.trie.TrieNode
hotpdf.trie.Trie
hotpdf.utils
hotpdf.processor
hotpdf.data.classes.HotCharacter
hotpdf.data.classes.Span
hotpdf.data.classes.ElementDimension
+45
View File
@@ -0,0 +1,45 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys
sys.path.insert(0, os.path.abspath("../.."))
project = "hotpdf"
copyright = "2024, Prestatech GmbH"
author = "Prestatech GmbH"
release = "0.1"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
"sphinx.ext.duration",
"sphinx.ext.doctest",
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.autosectionlabel",
]
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"sphinx": ("https://www.sphinx-doc.org/en/master/", None),
}
intersphinx_disabled_domains = ["std"]
templates_path = ["_templates"]
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "bizstyle"
@@ -0,0 +1,30 @@
hotpdf.data.classes.ElementDimension
====================================
.. currentmodule:: hotpdf.data.classes
.. autoclass:: ElementDimension
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~ElementDimension.__init__
.. rubric:: Attributes
.. autosummary::
~ElementDimension.span_id
~ElementDimension.x0
~ElementDimension.y0
~ElementDimension.x1
~ElementDimension.y1
@@ -0,0 +1,31 @@
hotpdf.data.classes.HotCharacter
================================
.. currentmodule:: hotpdf.data.classes
.. autoclass:: HotCharacter
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~HotCharacter.__init__
.. rubric:: Attributes
.. autosummary::
~HotCharacter.is_anno
~HotCharacter.value
~HotCharacter.x
~HotCharacter.y
~HotCharacter.x_end
~HotCharacter.span_id
@@ -0,0 +1,29 @@
hotpdf.data.classes.Span
========================
.. currentmodule:: hotpdf.data.classes
.. autoclass:: Span
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Span.__init__
~Span.get_element_dimension
~Span.to_text
.. rubric:: Attributes
.. autosummary::
~Span.characters
~Span.span_id
@@ -0,0 +1,23 @@
hotpdf.hotpdf.HotPdf
====================
.. currentmodule:: hotpdf.hotpdf
.. autoclass:: HotPdf
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~HotPdf.__init__
~HotPdf.extract_page_text
~HotPdf.extract_spans
~HotPdf.extract_spans_text
~HotPdf.extract_text
~HotPdf.find_text
~HotPdf.load
~HotPdf.merge_multiple
@@ -0,0 +1,20 @@
hotpdf.memory\_map.MemoryMap
============================
.. currentmodule:: hotpdf.memory_map
.. autoclass:: MemoryMap
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~MemoryMap.__init__
~MemoryMap.build_memory_map
~MemoryMap.extract_text_from_bbox
~MemoryMap.find_text
~MemoryMap.load_memory_map
@@ -0,0 +1,16 @@
hotpdf.processor
================
.. automodule:: hotpdf.processor
.. rubric:: Functions
.. autosummary::
process
@@ -0,0 +1,19 @@
hotpdf.span\_map.SpanMap
========================
.. currentmodule:: hotpdf.span_map
.. autoclass:: SpanMap
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~SpanMap.__init__
~SpanMap.get_span
~SpanMap.insert
~SpanMap.items
@@ -0,0 +1,18 @@
hotpdf.sparse\_matrix.SparseMatrix
==================================
.. currentmodule:: hotpdf.sparse_matrix
.. autoclass:: SparseMatrix
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~SparseMatrix.__init__
~SparseMatrix.get
~SparseMatrix.insert
@@ -0,0 +1,18 @@
hotpdf.trie.Trie
================
.. currentmodule:: hotpdf.trie
.. autoclass:: Trie
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Trie.__init__
~Trie.insert
~Trie.search_all
@@ -0,0 +1,16 @@
hotpdf.trie.TrieNode
====================
.. currentmodule:: hotpdf.trie
.. autoclass:: TrieNode
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~TrieNode.__init__
+20
View File
@@ -0,0 +1,20 @@
hotpdf.utils
============
.. automodule:: hotpdf.utils
.. rubric:: Functions
.. autosummary::
filter_adjacent_coords
find_neighbour_coord
get_element_dimension
intersect
to_text
+191
View File
@@ -0,0 +1,191 @@
==================
User Guide
==================
This guide contains a couple of common use cases that your application might have. Since HotPdf returns data in its own structure, its readability may not be optimal.
To mitigate this issue, we are writing this guide to help you get started with using HotPdf.
Text Operations
------------------------------------------
Start by loading the file.
The PDF can be loaded either by passing the file path or the file stream.
.. code-block:: python
from hotpdf import HotPdf
pdf_file_path = "path to your pdf file"
# Loading from path
hotpdf_document = HotPdf(pdf_file_path)
# Loading opened file
with open(pdf_file_path, "rb") as f:
hotpdf_document_2 = HotPdf(f)
Alternatively, to load a file, you can also defer loading from the constructor and using `.load()` instead.
.. code-block:: python
from hotpdf import HotPdf
pdf_file_path = "path to your pdf file"
# Loading from path
hotpdf_document = HotPdf()
hotpdf_document.load(pdf_file_path)
# Loading opened file
hotpdf_document_2 = HotPdf()
with open(pdf_file_path, "rb") as f:
hotpdf_document_2.load(f)
You can also merge multiple HotPdf objects to get one single HotPdf object!
.. code-block:: python
merged_hotpdf_object = HotPdf.merge_multiple(hotpdfs=[
hotpdf_document,
hotpdf_document2,
])
The `HotPdf` object has many attributes that you can use to solve your problems. One of them is `pages`, representing each page of the PDF stored in data structures (trie & sparse matrix) to help with text operations.
Locked PDFs can be loaded passing the password as the password argument:
.. code-block:: python
hotpdf_document = HotPdf()
hotpdf_document = hotpdf_document.load(locked_pdf_file_path, password="your_password")
Number of Pages
~~~~~~~~~~~~~~~~~~
Begin by getting the number of loaded pages or the total pages in the PDF.
.. code-block:: python
len_pages: int = len(hotpdf_document.pages)
Each `page` in the `pages` list is an in-memory representation of a page of the loaded PDF. All operations are performed on a page.
Looking up Text
~~~~~~~~~~~~~~~~~~
To look up text, use the `find_text` function.
You can attempt to find the full span the text lies in by setting `take_span` to `True`.
.. code-block:: python
text_occurrences = hotpdf_document.find_text("foo")
This will return a `dict` of `list` of `list` of `HotCharacter`:
- The `dict` keys are the page numbers.
- The outer `list` is all the occurrences found on the page.
- The inner `list` contains character-wise all the words that were found.
The `HotCharacter` object contains the value and the coordinates of the character on the PDF.
To get the entire span of the found occurrence, you could reuse the implementation of `get_element_dimension` that is found under `hotpdf.utils`.
.. code-block:: python
from hotpdf.utils import get_element_dimension
# Getting the dimension of the first element that was found on page 0.
element_dimension = get_element_dimension(text_occurrences[0][0])
`element_dimension` will return an `ElementDimension` data object which has the `x0`, `y0`, `x1`, `y1` values. These coordinates represent the position the text was found in.
You can set `take_span` to `True` to find the whole span that it lies in. Usage remains the same.
.. code-block:: python
text_occurrences = hotpdf_document.find_text("foo", take_span=True)
# Getting the dimension of the first element that was found on page 0.
element_dimension = get_element_dimension(text_occurrences[0][0])
For example, if you are looking for a text like "hotpdf v23" but you know that the part "v23" is variable, you can simply search for "hotpdf v" or just "hotpdf".
This will return the spans of the text as well, so you could also find "hotpdf v24" just by searching for "hotpdf v" or "hotpdf".
**Please note:** The text children of a `Span` depend on the PDF producing software, so it could be unpredictable. Either way, if it works for you, then it works. Please test it!
Extracting Text
~~~~~~~~~~~~~~~~~~
If you know the coordinates of the text that you are going to extract, you can use the `extract_text` function.
This will extract the text that lay in the specified coordinates (`x0`, `y0`, `x1`, `y1`) of the specified `page`.
If you don't specify a `page` it will default to 0 (i.e., the first page).
.. code-block:: python
text = pdf.extract_text(x0=0, y0=0, x1=600, y1=500, page=0)
This will return a `str` in plain text format. Characters, if they are on different lines, will be separated by `\n`.
Extracting Spans Text
~~~~~~~~~~~~~~~~~~~~~~
If you want to extract text of all spans that lay or intersect the coordinates (`x0`, `y0`, `x1`, `y1`) that you specify on the `page` that you specify, you need to use the `extract_spans_text` function.
In case you want more granular view of the spans, use `extract_spans` instead.
.. code-block:: python
text_spans = pdf.extract_spans_text(x0=0, y0=0, x1=600, y1=500, page=0)
This will return a `list` of `str`.
The `list` contains text of spans that lay within the given coordinates.
Extracting Spans
~~~~~~~~~~~~~~~~~~
If you want to extract all spans that lay or intersect the coordinates (`x0`, `y0`, `x1`, `y1`) that you specify on the `page` that you specify, you need to use the `extract_spans` function.
.. code-block:: python
text_spans = pdf.extract_spans(x0=0, y0=0, x1=600, y1=500, page=0)
This will return a `list` of `Span`.
The `list` contains the spans that lay within the given coordinates. A `Span` is a collection of `HotCharacter`
To access a span, you can access it by index. For example, if you want to get the dimensions of the first span that was returned, you can do this:
.. code-block:: python
from hotpdf.utils import get_element_dimension
# Get the dimensions of the first span
first_span_dimensions = spans[0].get_element_dimension()
# Get the text of the first span
span_text = spans[0].to_text()
This will give you the dimension of the span.
If you want to extract the text, you can iterate over a span and get the `value` attribute of the `HotCharacter`.
.. code-block:: python
extracted_span = "".join([hc.value for hc in text_spans[0]])
Extracting Text of Page
~~~~~~~~~~~~~~~~~~~~~~~~~
In case you want to view the text of a specified page, you can use the `extract_page_text` function.
This will return you an `str` of the whole page of the PDF.
.. code-block:: python
page_text = pdf.extract_page_text(page=0)
---
We will keep adding more functions to help with various operations. In any case please feel free to open an issue on our github.
+100
View File
@@ -0,0 +1,100 @@
=========
hotpdf
=========
This project was started as an internal project @ `Prestatech <http://prestatech.com/>`_ to parse PDF files in a fast and memory efficient way to overcome the difficulties we were having while parsing big PDF files using libraries such as `pdfquery <https://github.com/jcushman/pdfquery>`_.
hotpdf can be used to find and extract text from PDFs.
Installation
------------
The latest version of `hotpdf` can be installed directly from `PYPI`_ with pip.
.. code-block:: bash
pip install hotpdf
.. _PYPI: https://pypi.org/project/hotpdf/
Local Setup
------------
First install the dependencies required by hotpdf
.. code-block:: bash
python3 -m pip install -e .
Contributing
------------
You should install the `pre-commit` hooks with ``pre-commit install``. This will run the linter, mypy, and a subset of the tests on every commit.
For more examples of how to run the full test suite, please refer to the `CI workflow <https://github.com/weareprestatech/hotpdf/blob/main/.github/workflows/test.yml>`_.
We strive to keep the test coverage at 100%: if you want your contributions accepted, please write tests for them :D
Some examples of running tests locally:
.. code-block:: bash
python3 -m pip install -e '.[testing]' # install extra deps for testing
python3 -m pytest -n=auto test/ # run the test suite
# run tests with coverage
python3 -m pytest --cov-fail-under=96 -n=auto --cov=hotpdf --cov-report term-missing
Known Issues
--------------
1. (cid:x) characters in text - Some pdfs when extracted, some symbols like `€` might not be properly decoded, and instead be extracted as `(cid:128)`.
This is a problem with the `pdfminer.six` library. We have fixed it from our side on our `fork <https://github.com/weareprestatech/pdfminer.six>`, and you can install it using pip. Until we are able to merge it to pdfminer.six repo and it gets released, we recommend that you install our fork with the fixes manually.
.. code-block:: bash
pip install --no-cache-dir git+https://github.com/weareprestatech/pdfminer.six.git@20240222#egg=pdfminer-six
Documentation
--------------
We use `sphinx <https://www.sphinx-doc.org/en/master/>`_ for generating our docs and host them on `readthedocs <https://readthedocs.org/>`_.
Please update and add documentation if required, with your contributions.
Update the `.rst` files, rebuild them, and commit them along with your PRs.
.. code-block:: bash
cd docs
make clean
make html
This will generate the necessary documentation files. Once merged to `main` the docs will be updated automatically.
Contents
--------------
To view detailed usage information, please navigate to `Usage` and `User Guide`
.. toctree::
:maxdepth: 3
:caption: Contents:
usage
guide
api
License
-------
This project is licensed under the terms of the MIT license.
---
with ❤️ from the team @ `Prestatech GmbH <https://prestatech.com/>`_
+160
View File
@@ -0,0 +1,160 @@
=========
Usage
=========
HotPdf Class
------------------------------------------
.. autoclass:: hotpdf.HotPdf
.. autofunction:: hotpdf.HotPdf.__init__
The HotPdf class is the wrapper around your PDF that allows for searching text and extracting text on your PDFs.
.. code-block:: python
from hotpdf import HotPdf
pdf_file_path = "path to your pdf file"
# Load directly from Path
hotpdf_document = HotPdf(pdf_file_path)
# Load from file stream
with open(pdf_file_path, "rb") as f:
hotpdf_document_2 = HotPdf(f)
Alternatively you can defer loading, and use the `.load()` function instead. The outcome is the same, internally the constructor for `HotPdf` calls the `.load()` function
.. code-block:: python
from hotpdf import HotPdf
pdf_file_path = "path to your pdf file"
# path
hotpdf_document = HotPdf()
hotpdf_document = hotpdf_document.load(pdf_file_path)
# file stream
hotpdf_document_2 = HotPdf()
with open(pdf_file_path, "rb") as f:
hotpdf_document_2 = hotpdf_document_2.load(f)
.. autofunction:: hotpdf.HotPdf.load
You can also merge multiple HotPdf objects to get one single HotPdf object!
.. code-block:: python
merged_hotpdf_object = HotPdf.merge_multiple(hotpdfs=[
hotpdf_document,
hotpdf_document2,
])
.. autofunction:: hotpdf.HotPdf.merge_multiple
File Operations
------------------------------------------
Length
~~~~~~~~~~~~~~~~~~~
The number of pages in the PDF file can be determined by checking the `len` of `pages` property of the hotpdf object.
.. code-block:: python
num_pages = len(hotpdf_document.pages)
Search
------------------------------------------
find_text
~~~~~~~~~~~~~~~~~~~
To look for a string in the entire PDF File, you can use the `find_text` function.
You can also specify what pages you want to search in. By default it will look through the whole PDF.
To get the whole span where the string lies in, you can set `take_span` to True.
.. code-block:: python
text_occurences = hotpdf_document.find_text("foo")
text_occurences_with_span = hotpdf_document.find_text(
"foo",
take_span=True,
)
.. autofunction:: hotpdf.HotPdf.find_text
Extraction
------------------------------------------
extract_text
~~~~~~~~~~~~~~~~~~~
To extract string from specific positions in the PDF, you can use the `extract_text` function.
This will extract the string that lies within the positions that have been specified on the page that it's specified (default is Page 0).
.. code-block:: python
text_in_bbox = hotpdf_document.extract_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
.. autofunction:: hotpdf.HotPdf.extract_text
extract_spans
~~~~~~~~~~~~~~~~~~~
Instead of just the individual characters that lay within the bounds that you specify, if you want full words, or the complete spans that intersect within the specified bounds - you can use the `extract_spans` functions instead.
This will extract all the spans that intersect with the positions that have been specified on the page that it's specified (default is Page 0).
.. code-block:: python
spans_in_bbox = hotpdf_document.extract_spans(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
.. autofunction:: hotpdf.HotPdf.extract_spans
extract_spans_text
~~~~~~~~~~~~~~~~~~~
Instead of handling the spans structures yourself, if you are only interested in the text of the spans, you can use the `extract_spans_text` function instead.
The function is the same as `extract_spans`_ except it returns you a `list` of `str`.
.. code-block:: python
spans_text_in_bbox = hotpdf_document.extract_spans_text(
x0=0,
y0=0,
x1=100,
y1=10,
page=0,
)
.. autofunction:: hotpdf.HotPdf.extract_spans_text
extract_page_text
~~~~~~~~~~~~~~~~~~~
If you want to view the text of an entire page in plaintext `str` format, you can use the `extract_page_text` function.
The function accepts `page` as a parameter.
.. code-block:: python
page_text = hotpdf_document.extract_page_text(page=0,)
.. autofunction:: hotpdf.HotPdf.extract_page_text
+4
View File
@@ -0,0 +1,4 @@
from hotpdf.hotpdf import HotPdf
__version__ = "0.1.0"
__all__ = ["HotPdf"]
View File
+94
View File
@@ -0,0 +1,94 @@
from collections import defaultdict
from dataclasses import dataclass
from typing import Optional
from uuid import UUID
@dataclass
class HotCharacter:
"""A hot character is a character on a page with certain attributes.
Attributes:
value (str): value value of the character.
x (int): x position of the character - column number.
y (int): y position of the character - row number.
x_end (int): end x position of the character. x_end - x = width of character.
span_id (UUID): hash of parent span the character lies in.
is_anno (bool, Optional): specify if a character is an annotation (default: False).
"""
value: str
x: int
y: int
x_end: int
span_id: UUID
is_anno: Optional[bool] = False
@dataclass
class ElementDimension:
"""ElementDimension is the dimension of an element in hotpdf.
Attributes:
x0 (int): starting x position of the element (column).
y0 (int): starting y position of the element (row).
x1 (int): end x position of the element (column). x1 - x0 = width.
y1 (int): end y position of the element (row) y1 - y0 = height.
span_id (UUID, Optional): hash of parent span the element lies in.
"""
x0: int
y0: int
x1: int
y1: int
span_id: Optional[UUID] = None
@dataclass(init=True)
class Span:
"""A span is a group of characters that are close to each other.
Attributes:
characters (list[HotCharacter]): list of characters in the span.
x0 (int): starting x position of the span (column).
y0 (int): starting y position of the span (row).
x_end (int): end x position of the span (column). x_end - x0 = width.
span_id (UUID, Optional): hash of the span.
"""
characters: list[HotCharacter]
span_id: UUID
def to_text(self) -> str:
"""Convert the span to text.
Returns:
str: text representation of the span.
"""
return "".join(char.value for char in self.characters)
def get_element_dimension(self) -> ElementDimension:
"""Get the element dimension of the span.
Raises:
ValueError: if the span has no characters.
Returns:
ElementDimension: _description_
"""
if not self.characters:
raise ValueError("Span has no characters")
x0 = self.characters[0].x
y0 = self.characters[0].y
x1 = self.characters[-1].x_end
y1 = self.characters[-1].y
return ElementDimension(x0, y0, x1, y1, self.span_id)
# All occurences of HotCharacters in a page
# A list[HotCharacter] is the representation of a word split into "HotCharacters"
# A list[list[HotCharacter]] is a list of multiple list[HotCharacter] found on a page
PageResult = list[list[HotCharacter]]
# Complete PageResult with Page Number as the index
SearchResult = defaultdict[int, PageResult]
View File
+2
View File
@@ -0,0 +1,2 @@
class HotPdfIsNoneError(Exception):
pass
+361
View File
@@ -0,0 +1,361 @@
import math
import os
from collections import defaultdict
from io import IOBase
from pathlib import PurePath
from typing import Optional, Union
from hotpdf import processor
from hotpdf.exceptions.custom_exceptions import HotPdfIsNoneError
from hotpdf.memory_map import MemoryMap
from hotpdf.utils import filter_adjacent_coords, intersect
from .data.classes import ElementDimension, HotCharacter, PageResult, SearchResult, Span
class HotPdf:
def __init__(
self,
pdf_file: Union[PurePath, str, IOBase, None] = None,
password: str = "",
page_numbers: Optional[list[int]] = None,
extraction_tolerance: int = 4,
laparams: Optional[dict[str, Union[float, bool]]] = None,
include_annotation_spaces: bool = False,
preserve_pdfminer_coordinates: bool = False,
) -> None:
"""Initialize the HotPdf class.
Args:
pdf_file (PurePath | str | IOBytes): The path to the PDF file to be loaded, or a bytes object.
password (str, optional): Password to use to unlock the pdf
page_numbers (list[int], optional): Pages to be loaded into memory. (0-indexed).
If not provided, will load all pages (default).
extraction_tolerance (int, optional): Tolerance value used during text extraction
to adjust the bounding box for capturing text. Defaults to 4.
laparams (dict[str, Union[float, bool]], optional): Layout parameters for pdfminer.
include_annotation_spaces (bool, optional): Add annotation spaces to the memory map. Default: False
preserve_pdfminer_coordinates (bool, Optional): Preserve pdfminer y-coordinate values.
Default: False - use natural coords
Raises:
ValueError: If the page range is invalid.
FileNotFoundError: If the file is not found.
PermissionError: If the file is encrypted or the password is wrong.
RuntimeError: If an unknown error is generated by transfotmer.
"""
self.pages: list[MemoryMap] = []
self.extraction_tolerance: int = extraction_tolerance
if pdf_file:
self.load(
pdf_file,
password,
page_numbers,
laparams=laparams,
include_annotation_spaces=include_annotation_spaces,
preserve_pdfminer_coordinates=preserve_pdfminer_coordinates,
)
def __check_file_exists(self, pdf_file: str) -> None:
if not os.path.exists(pdf_file):
raise FileNotFoundError(f"File {pdf_file} not found")
def __check_coordinates(self, x0: int, y0: int, x1: int, y1: int) -> None:
if x0 < 0 or x1 < 0 or y0 < 0 or y1 < 0:
raise ValueError("Invalid coordinates")
def __check_page_number(self, page: int) -> None:
if page < 0 or page >= len(self.pages):
raise ValueError("Invalid page number")
def __check_page_numbers(self, pages: list[int]) -> None:
for page in pages:
self.__check_page_number(page)
def __check_page_range(self, page_numbers: list[int]) -> None:
if any(_page_num < 0 for _page_num in page_numbers):
raise ValueError("Invalid page range")
def __prechecks(self, pdf_file: Union[PurePath, str, IOBase], page_numbers: list[int]) -> None:
if type(pdf_file) is str:
self.__check_file_exists(pdf_file)
self.__check_page_range(page_numbers)
@staticmethod
def merge_multiple(
hotpdfs: list["HotPdf"],
) -> "HotPdf":
"""Merge multiple HotPdf objects and return a single HotPdf object consisting of all pages
Args:
hotpdfs (list[HotPdf]): List of HotPdf objects that will be combined
to form one single HotPdf object. All other params will be ignored in this case.
Raises:
HotPdfIsNoneError: If any of the HotPdf objects in the hotpdfs list is None
Returns:
HotPdf: Merged HotPdf object
"""
if any(_hotpdf is None for _hotpdf in hotpdfs):
raise HotPdfIsNoneError("HotPdf object cannot be None")
merged_hotpdf = HotPdf()
for _hotpdf in hotpdfs:
merged_hotpdf.pages.extend(_hotpdf.pages)
return merged_hotpdf
def load(
self,
pdf_file: Union[PurePath, str, IOBase],
password: str = "",
page_numbers: Optional[list[int]] = None,
laparams: Optional[dict[str, Union[float, bool]]] = None,
include_annotation_spaces: bool = False,
preserve_pdfminer_coordinates: bool = False,
) -> None:
"""Load a PDF file into memory.
Args:
pdf_file (str | Bytes): The path to the PDF file to be loaded, or a bytes object.
password (str, optional): Password to use to unlock the pdf
page_numbers (list[int], optional): Pages to be loaded into memory. (0-indexed).
If not provided, will load all pages (default).
laparams (dict[str, Union[float, bool]], optional): Layout parameters for pdfminer.
include_annotation_spaces (bool, optional): Add annotation spaces to the memory map.
preserve_pdfminer_coordinates (bool, Optional): Preserve pdfminer y-coordinate values.
Default: False - use natural coords
Raises:
Exception: If an unknown error is generated by pdfminer.
"""
page_numbers = page_numbers or []
self.__prechecks(pdf_file, page_numbers)
try:
self.pages = processor.process(
source=pdf_file,
password=password,
page_numbers=page_numbers,
laparams=laparams,
include_annotation_spaces=include_annotation_spaces,
preserve_pdfminer_coordinates=preserve_pdfminer_coordinates,
)
except Exception as e:
raise e
def __extract_full_text_span(
self,
hot_characters: list[HotCharacter],
page_num: int,
) -> Union[list[HotCharacter], None]:
"""Extract the full span of text that the given hot characters are a part of.
Args:
hot_characters (list[HotCharacter]): the list of hot characters to extract the span for.
page_num (int): the page number of the hot characters.
Returns:
Union[list[HotCharacter], None]: the full span of text that the hot characters are a part of.
"""
_span: Optional[Span] = None
if hot_characters[0].span_id:
_span = self.pages[page_num].span_map[hot_characters[0].span_id]
return _span.characters if _span else None
def find_text(
self,
query: str,
pages: Optional[list[int]] = None,
take_span: bool = False,
sort: bool = True,
case_sensitive: bool = True,
) -> SearchResult:
"""Find text within the loaded PDF pages.
Args:
query (str): The text to search for.
pages (list[int], optional): List of page numbers to search.
take_span (bool, optional): Take the full span of the text that it is a part of.
sort (bool, Optional): Return elements sorted by their positions.
case_sensitive (bool, optional): Whether the search should be case-sensitive. Defaults to True.
Raises:
ValueError: If the page number is invalid.
Returns:
SearchResult: A dictionary mapping page numbers to found text coordinates.
"""
pages = pages or []
self.__check_page_numbers(pages)
query_pages = (
{i: self.pages[i] for i in range(len(self.pages))} if len(pages) == 0 else {i: self.pages[i] for i in pages}
)
found_page_map = {}
normalized_query = query if case_sensitive else query.lower()
for page_num in query_pages:
found_page_map[page_num] = filter_adjacent_coords(
*query_pages[page_num].find_text(query, case_sensitive=case_sensitive)
)
final_found_page_map: SearchResult = defaultdict(PageResult)
for page_num in found_page_map:
hot_character_page_occurences: PageResult = found_page_map[page_num]
final_found_page_map[page_num] = []
for hot_characters in hot_character_page_occurences:
text = "".join(hc.value for hc in hot_characters)
comparable_text = text if case_sensitive else text.lower()
if normalized_query not in comparable_text:
continue
full_span_dimension_hot_characters: Union[list[HotCharacter], None] = (
self.__extract_full_text_span(
hot_characters=hot_characters,
page_num=page_num,
)
if take_span
else None
)
chars_to_append = (
full_span_dimension_hot_characters
if (take_span and full_span_dimension_hot_characters)
else hot_characters
)
if chars_to_append and sort:
chars_to_append = sorted(chars_to_append, key=lambda ch: (ch.y, ch.x))
final_found_page_map[page_num].append(chars_to_append)
if sort:
for _page in final_found_page_map:
final_found_page_map[_page] = sorted(
final_found_page_map[_page], key=lambda element: (element[0].y, element[0].x)
)
return final_found_page_map
def extract_spans(self, x0: int, y0: int, x1: int, y1: int, page: int = 0, sort: bool = True) -> list[Span]:
"""Extract spans that intersect with the given bounding box.
Args:
x0 (int): The left x-coordinate of the bounding box.
y0 (int): The bottom y-coordinate of the bounding box.
x1 (int): The right x-coordinate of the bounding box.
y1 (int): The top y-coordinate of the bounding box.
page (int, optional): The page number. Defaults to 0.
sort (bool, optional): Sort the spans by their coordinates. Defaults to True.
Raises:
ValueError: If the coordinates are invalid.
ValueError: If the page number is invalid.
Returns:
list[Span]: List of spans of hotcharacters that intersect with the given bounding box
"""
spans: list[Span] = []
self.__check_coordinates(x0, y0, x1, y1)
self.__check_page_number(page)
for _, span in self.pages[page].span_map.items():
if intersect(ElementDimension(x0, y0, x1, y1, None), span.get_element_dimension()):
span.characters = sorted(span.characters, key=lambda ch: (ch.y, ch.x))
spans.append(span)
if sort:
spans = sorted(
spans, key=lambda span: (span.get_element_dimension().y0, span.get_element_dimension().x0)
)
return spans
def extract_text(
self,
x0: int,
y0: int,
x1: int,
y1: int,
page: int = 0,
) -> str:
"""Extract text from a specified bounding box on a page.
Args:
x0 (int): The left x-coordinate of the bounding box.
y0 (int): The bottom y-coordinate of the bounding box.
x1 (int): The right x-coordinate of the bounding box.
y1 (int): The top y-coordinate of the bounding box.
page (int): The page number. Defaults to 0.
Raises:
ValueError: If the coordinates are invalid.
ValueError: If the page number is invalid.
Returns:
str: Extracted text within the bounding box.
"""
self.__check_coordinates(x0, y0, x1, y1)
self.__check_page_number(page)
page_to_search: MemoryMap = self.pages[page]
extracted_text = page_to_search.extract_text_from_bbox(
x0=math.floor(x0),
x1=math.ceil(x1 + self.extraction_tolerance),
y0=y0,
y1=y1,
)
return extracted_text
def extract_page_text(
self,
page: int,
) -> str:
"""Extract text from a specified page.
Args:
page (int): The page number.
Raises:
ValueError: If the page number is invalid.
Returns:
str: Extracted text from the page.
"""
self.__check_page_number(page)
page_to_search: MemoryMap = self.pages[page]
extracted_text = page_to_search.extract_text_from_bbox(
x0=0,
x1=page_to_search.width,
y0=0,
y1=page_to_search.height,
)
return extracted_text
def extract_spans_text(
self,
x0: int,
y0: int,
x1: int,
y1: int,
page: int = 0,
) -> str:
"""Extract text from spans that intersect with the given bounding box.
Args:
x0 (int): The left x-coordinate of the bounding box.
y0 (int): The bottom y-coordinate of the bounding box.
x1 (int): The right x-coordinate of the bounding box.
y1 (int): The top y-coordinate of the bounding box.
page (int, optional): The page number. Defaults to 0.
Raises:
ValueError: If the coordinates are invalid.
ValueError: If the page number is invalid.
Returns:
str: Extracted text that intersects with the bounding box.
"""
self.__check_coordinates(x0, y0, x1, y1)
self.__check_page_number(page)
spans: list[Span] = self.extract_spans(x0, y0, x1, y1, page)
extracted_text: list[str] = []
for span in spans:
extracted_text.append(span.to_text())
return "".join(extracted_text)
+250
View File
@@ -0,0 +1,250 @@
import math
from collections import defaultdict
from collections.abc import Generator
from typing import Union
from uuid import UUID, uuid4
from pdfminer.layout import LTAnno, LTChar, LTComponent, LTFigure, LTPage, LTText, LTTextContainer, LTTextLine
from .data.classes import HotCharacter, PageResult
from .span_map import SpanMap
from .sparse_matrix import SparseMatrix
from .trie import Trie
class MemoryMap:
def __init__(self) -> None:
"""Initialize the MemoryMap. 2D Matrix representation of a PDF Page.
Args:
width (int): The width of a page.
height (int) The height of a page.
"""
self.text_trie = Trie()
self.span_map = SpanMap()
self.width: int = 0
self.height: int = 0
def build_memory_map(self) -> None:
"""Build the memory map based on width and height.
The memory map is a SparseMatrix representation of the PDF.
"""
self.memory_map = SparseMatrix()
def __reverse_page_objs(self, page_objs: list[LTComponent]) -> Generator[LTComponent, None, None]:
yield from reversed(page_objs)
def __extract_from_ltfigure(self, lt_figure_obj: LTFigure) -> Generator[Union[LTTextLine, LTChar], None, None]:
for element in lt_figure_obj:
if isinstance(element, (LTTextLine, LTChar)):
yield element
elif isinstance(element, LTTextContainer):
element_stack = self.__reverse_page_objs(list(element))
yield from (em for em in element_stack if isinstance(em, LTTextLine))
def __get_page_spans(self, page: LTPage) -> Generator[Union[LTTextLine, LTChar], None, None]:
element_stack = self.__reverse_page_objs(page._objs)
for obj in element_stack:
if isinstance(obj, LTTextLine):
yield obj
elif isinstance(obj, (LTTextContainer)):
element_stack = self.__reverse_page_objs(list(obj))
yield from (em for em in element_stack if isinstance(em, LTTextLine))
elif isinstance(obj, (LTFigure)):
yield from self.__extract_from_ltfigure(obj)
def __get_right_shifted_hot_character(self, hot_character: HotCharacter, shift: int) -> HotCharacter:
"""Shift a hotcharacter on the x-coordinate
Args:
hot_character (HotCharacter): HotCharacter object to be shifted
shift (int): shift offset on the x-coordinate
Returns:
HotCharacter: HotCharacter object with new coords
"""
hot_character.x += shift
hot_character.x_end += shift
return hot_character
def load_memory_map(
self,
page: LTPage,
include_annotation_spaces: bool = False,
preserve_pdfminer_coordinates: bool = False,
) -> None:
"""Load memory map data from an XML page.
Args:
page (str): LTPage Element returned by pdfminer
include_annotation_spaces (bool, optional): Add annotation spaces to the memory map.
preserve_pdfminer_coordinates(bool, optional): Preserve pdfminer y-coordinate values.
Returns:
None
"""
char_hot_characters: list[HotCharacter] = []
page_components: Generator[Union[LTTextLine, LTChar], None, None] = self.__get_page_spans(page)
line_shift: defaultdict[int, int] = defaultdict(int)
for component in page_components:
span_id = uuid4()
prev_char_inserted = False
if isinstance(component, LTChar):
x0 = round(component.x0)
x1 = round(component.x1)
y0 = round(component.y0) if preserve_pdfminer_coordinates else round(page.height - component.y0)
hot_character: HotCharacter = self.__get_hot_character_of(
value=component.get_text(),
x=x0,
y=y0,
x_end=x1,
span_id=span_id,
)
char_hot_characters.append(
hot_character,
)
continue
for character in component:
if (
include_annotation_spaces
and isinstance(character, LTAnno)
and (character._text == " ")
and prev_char_inserted
):
_elem_width: int = 1
space_char: HotCharacter = self.__get_hot_character_of(
value=" ", x=x0, y=y0, x_end=x0 + _elem_width, span_id=span_id, is_anno=True
)
char_hot_characters.append(
space_char,
)
prev_char_inserted = False
elif (
isinstance(character, (LTChar, LTText))
and (
hasattr(character, "x0")
and hasattr(character, "x1")
and hasattr(character, "y0")
and hasattr(character, "y1")
)
and not isinstance(character, LTAnno)
):
char_c = character.get_text()
x0 = round(character.x0)
x1 = round(character.x1)
y0 = round(component.y0) if preserve_pdfminer_coordinates else round(page.height - component.y0)
hot_character = self.__get_hot_character_of(
value=char_c,
x=x0,
y=y0,
x_end=x1,
span_id=span_id,
)
char_hot_characters.append(
hot_character,
)
prev_char_inserted = char_c != " "
# Insert into Trie and Span Maps
last_inserted_x_y: tuple[int, int] = (-1, -1)
for i in range(len(char_hot_characters)):
_current_character: HotCharacter = char_hot_characters[i]
# Determine if annotation spaces should be added
if include_annotation_spaces and i > 0 and i < len(char_hot_characters) - 1:
prev_char: HotCharacter = char_hot_characters[i - 1]
next_char: HotCharacter = char_hot_characters[i + 1]
# Anno and non-anno characters should not be overlapping
if _current_character.is_anno and next_char.x - prev_char.x <= 0:
continue
# Prevent characters from overlapping
if (last_inserted_x_y[0] > 0 and last_inserted_x_y[1] > 0) and (
_current_character.x == last_inserted_x_y[0] and _current_character.y == last_inserted_x_y[1]
):
line_shift[_current_character.y] += 1
last_inserted_x_y = (_current_character.x, _current_character.y)
_current_character = self.__get_right_shifted_hot_character(
_current_character, line_shift[_current_character.y]
)
self.__insert_hotcharacter_to_memory(_current_character)
self.width = math.ceil(page.width)
self.height = math.ceil(page.height)
def __insert_hotcharacter_to_memory(
self,
hot_character: HotCharacter,
) -> None:
"""Insert hotcharacter into memory map & trie"""
if hot_character.value == "":
return None
self.memory_map.insert(value=hot_character.value, row_idx=hot_character.y, column_idx=hot_character.x)
self.text_trie.insert(word=hot_character.value, hot_character=hot_character)
if hot_character.span_id:
self.span_map[hot_character.span_id] = hot_character
def __get_hot_character_of(
self,
value: str,
x: int,
y: int,
x_end: int,
span_id: UUID,
is_anno: bool = False,
) -> HotCharacter:
"""Insert element into memory map.
Args:
value (str): Value of the object to be inserted.
x (int): column index (x0-coordinate) of the element.
y (int): row index (y0-coordinate) of the element.
x_end (int): end column index (x1-coordinate) of element. x_end - x = width of element.
span_id (UUID): id of parent span.
Returns:
HotCharacter: HotCharacter object of the whitespace.
"""
return HotCharacter(
value=value,
x=x,
y=y,
x_end=x_end,
span_id=span_id,
is_anno=is_anno,
)
def extract_text_from_bbox(self, x0: int, x1: int, y0: int, y1: int) -> str:
"""Extract text within a specified bounding box.
Args:
x0 (int): Left x-coordinate of the bounding box.
x1 (int): Right x-coordinate of the bounding box.
y0 (int): Bottom y-coordinate of the bounding box.
y1 (int): Top y-coordinate of the bounding box.
Returns:
str: Extracted text within the bounding box.
"""
extracted_text: str = ""
for row in range(max(y0, 0), min(y1, self.memory_map.rows - 1) + 1):
row_text: str = ""
row_text = "".join(
self.memory_map.get(row_idx=row, column_idx=col)
for col in range(max(x0, 0), min(x1, self.memory_map.columns - 1) + 1)
)
if row_text:
extracted_text += row_text + "\n"
return extracted_text
def find_text(self, query: str, case_sensitive: bool = True) -> tuple[list[str], PageResult]:
"""Find text within the memory map.
Args:
query (str): The text to search for.
case_sensitive (bool): Whether the search should be case-sensitive. Defaults to True.
Returns:
list: List of found text coordinates.
"""
found_text = self.text_trie.search_all(query, case_sensitive=case_sensitive)
return found_text
+73
View File
@@ -0,0 +1,73 @@
import logging
from io import IOBase
from pathlib import PurePath
from typing import Optional, Union
from pdfminer.high_level import extract_pages
from pdfminer.layout import LAParams
from hotpdf.memory_map import MemoryMap
logging.getLogger("pdfminer").setLevel(logging.ERROR)
def __make_custom_laparams_object(
laparams: Optional[dict[str, Union[float, bool]]] = None,
) -> Union[LAParams, None]:
if not laparams:
return None
laparams_obj: LAParams = LAParams()
for key in laparams:
if hasattr(laparams_obj, key):
laparams_obj.__setattr__(key, laparams[key])
return laparams_obj
def __supress_pdfminer_logs() -> None:
logging.getLogger("pdfminer").setLevel(logging.ERROR)
def __process(
source: Union[PurePath, str, IOBase],
password: str = "",
page_numbers: Optional[list[int]] = None,
laparams: Optional[dict[str, Union[float, bool]]] = None,
include_annotation_spaces: bool = False,
preserve_pdfminer_coordinates: bool = False,
) -> list[MemoryMap]:
pages: list[MemoryMap] = []
__supress_pdfminer_logs()
page_numbers = sorted(page_numbers) if page_numbers else []
laparams_obj = __make_custom_laparams_object(laparams)
hl_page_layouts = extract_pages(
source, password=password, page_numbers=page_numbers, caching=True, laparams=laparams_obj
)
for page_layout in hl_page_layouts:
parsed_page: MemoryMap = MemoryMap()
parsed_page.build_memory_map()
parsed_page.load_memory_map(
page=page_layout,
include_annotation_spaces=include_annotation_spaces,
preserve_pdfminer_coordinates=preserve_pdfminer_coordinates,
)
pages.append(parsed_page)
return pages
def process(
source: Union[PurePath, str, IOBase],
password: str = "",
page_numbers: Optional[list[int]] = None,
laparams: Optional[dict[str, Union[float, bool]]] = None,
include_annotation_spaces: bool = False,
preserve_pdfminer_coordinates: bool = False,
) -> list[MemoryMap]:
return __process(
source=source,
password=password,
page_numbers=page_numbers,
laparams=laparams,
include_annotation_spaces=include_annotation_spaces,
preserve_pdfminer_coordinates=preserve_pdfminer_coordinates,
)
+45
View File
@@ -0,0 +1,45 @@
from collections.abc import Iterable
from typing import Union
from uuid import UUID
from .data.classes import HotCharacter, Span
class SpanMap:
"""Hashmap to store spans and their child words for fast referencing
and character grouping.
Keys are span_ids and values are Span objects.
"""
def __init__(self) -> None:
self.span_map: dict[UUID, Span] = dict()
def __len__(self) -> int:
return len(self.span_map)
def __getitem__(self, span_id: UUID) -> Union[Span, None]:
return self.get_span(span_id)
def __setitem__(self, span_id: UUID, hot_character: HotCharacter) -> None:
self.insert(span_id, hot_character)
def items(self) -> Iterable[tuple[UUID, Span]]:
yield from self.span_map.items()
def insert(self, span_id: UUID, hot_character: HotCharacter) -> None:
span = self.span_map.get(span_id)
if not span:
span = Span(
characters=[],
span_id=span_id,
)
span.characters.append(hot_character)
self.span_map[span_id] = span
def get_span(self, span_id: UUID) -> Union[Span, None]:
span = self.span_map.get(span_id)
if not span:
return None
span.characters = sorted(span.characters, key=lambda ch: (ch.y, ch.x))
return span
+60
View File
@@ -0,0 +1,60 @@
from collections import defaultdict
from collections.abc import Iterator
from warnings import warn
class SparseMatrix:
"""2D representation of a PDF in plain text format.
Sparse matrix removes the need to keep in memory the blank spaces
that are present in a PDF. Thus reducing memory usage drastically.
"""
def __init__(self, rows: int = 0, columns: int = 0):
self.values: defaultdict[tuple[int, int], str] = defaultdict(str)
self.rows = rows
self.columns = columns
def __getitem__(self, key: tuple[int, int]) -> str:
row_idx, column_idx = key
self.__check_indices(row_idx, column_idx)
return self.values[(row_idx, column_idx)]
def __update_indices(self, row_idx: int, column_idx: int) -> None:
if row_idx > self.rows:
self.rows = row_idx + 1
if column_idx > self.columns:
self.columns = column_idx + 1
def __check_indices(self, row_idx: int, column_idx: int) -> None:
if row_idx < 0 or column_idx < 0:
raise IndexError("Specified index is out of range")
def __setitem__(self, key: tuple[int, int], value: str) -> None:
row_idx, column_idx = key
try:
self.__check_indices(row_idx, column_idx)
except IndexError as ie:
warn("Index Error. Skipping insertion into SparseMatrix", stacklevel=1)
warn(str(ie), stacklevel=1)
return
self.__update_indices(row_idx, column_idx)
if value:
self.values[(row_idx, column_idx)] = value
def __iter__(self) -> Iterator[tuple[tuple[int, int], str]]:
yield from self.values.items()
def insert(self, value: str, row_idx: int, column_idx: int) -> None:
self.__update_indices(row_idx, column_idx)
try:
self.__check_indices(row_idx, column_idx)
except IndexError:
warn("Index Error. Skipping insertion into SparseMatrix", stacklevel=1)
return
if value:
self.values[(row_idx, column_idx)] = value
def get(self, row_idx: int, column_idx: int) -> str:
self.__check_indices(row_idx, column_idx)
return self.values[(row_idx, column_idx)]
+66
View File
@@ -0,0 +1,66 @@
from collections import defaultdict
from .data.classes import HotCharacter, PageResult
class TrieNode:
def __init__(self) -> None:
"""Initialize a TrieNode.
Args:
children (dict): Mapping of characters to TrieNode objects.
is_end_of_word (bool): Flag indicating the end of a word.
hot_characters (list[HotCharacter]): List of HotCharacter instances associated with the word.
"""
self.children: defaultdict[str, TrieNode] = defaultdict(TrieNode)
self.is_end_of_word: bool = False
self.hot_characters: list[HotCharacter] = []
class Trie:
def __init__(self) -> None:
"""Initialize a Trie."""
self.root = TrieNode()
def insert(self, word: str, hot_character: HotCharacter) -> None:
"""Insert a word and a HotCharacter into the Trie.
Args:
word (str): The word to insert.
hot_character (HotCharacter): The HotCharacter to insert.
"""
node: TrieNode = self.root
for char in word:
node = node.children[char]
node.is_end_of_word = True
node.hot_characters = node.hot_characters + [hot_character]
def search_all(self, text: str, case_sensitive: bool = True) -> tuple[list[str], PageResult]:
"""Search for words in the Trie that match a given text.
Args:
text (str): The text to search for.
case_sensitive (bool): Whether the search should be case-sensitive. Defaults to True.
Returns:
tuple: A tuple containing a list of the target characters found and corresponding PageResult.
"""
node: TrieNode = self.root
found: list[str] = []
hot_characters: PageResult = []
for char in text:
if case_sensitive:
if char in node.children and node.children[char].is_end_of_word:
found.append(char)
if node.children[char].hot_characters:
hot_characters.append(node.children[char].hot_characters)
else:
combined_hot_chars = []
for candidate in {char, char.lower(), char.upper()}:
if candidate in node.children and node.children[candidate].is_end_of_word:
combined_hot_chars.extend(node.children[candidate].hot_characters)
if combined_hot_chars:
found.append(char)
hot_characters.append(combined_hot_chars)
node = self.root
return found, hot_characters
+119
View File
@@ -0,0 +1,119 @@
from typing import Union
from .data.classes import ElementDimension, HotCharacter, PageResult
def find_neighbour_coord(
reference_character: HotCharacter,
hot_characters: list[HotCharacter],
max_distance: int = 5,
span_tolerance: int = 5,
) -> Union[HotCharacter, None]:
"""Find a neighbouring coordinate within a specified maximum distance.
Args:
reference_character (HotCharacter): Previous char instance.
hot_characters (list[HotCharacter]): List of character instances to search through.
max_distance (int): Maximum distance between reference coordinate and target coordinate.
span_tolerance (int): Additional distance to consider if text lies in the same span.
Returns:
HotCharacter: The neighbouring HotCharacter if found, else None.
"""
for hot_character in hot_characters:
if hot_character == reference_character:
continue
if (
(
0
<= (hot_character.x - reference_character.x_end)
<= (
(max_distance + span_tolerance)
if hot_character.span_id == reference_character.span_id
and (hot_character.span_id and reference_character.span_id)
else max_distance
)
)
or (reference_character.span_id == hot_character.span_id and reference_character.x < hot_character.x)
and (hot_character.x <= reference_character.x_end)
) and reference_character.y == hot_character.y:
return hot_character
return None
def filter_adjacent_coords(text: list[str], page_hot_character_occurences: PageResult) -> PageResult:
"""Filter adjacent coordinates based on the given text.
Args:
text (str): The text to filter by.
page_hot_character_occurences (list): List of coordinates to filter by page
Returns:
PageResult: List of adjacent groups of HotCharacters on a page.
"""
if not page_hot_character_occurences:
return []
max_len = len(text)
adjacent_groups = []
anchor_hot_character_instances = page_hot_character_occurences[0]
for anchor_hot_character in anchor_hot_character_instances:
neighbours = [anchor_hot_character]
reference_hot_character = anchor_hot_character
for coords_j in page_hot_character_occurences[1:]:
neighbour_hot_character = find_neighbour_coord(
reference_character=reference_hot_character,
hot_characters=coords_j,
)
if neighbour_hot_character:
neighbours.append(neighbour_hot_character)
reference_hot_character = neighbour_hot_character
if len(neighbours) == max_len:
adjacent_groups.append(neighbours[:])
neighbours.clear()
neighbours = []
return adjacent_groups
def get_element_dimension(elem: list[HotCharacter]) -> ElementDimension:
"""Get the dimensions of an element based on its coordinates.
Args:
elem (list): List of coordinates representing an element.
Returns:
ElementDimension: ElementDimension object containing the dimensions (x0, x1, y0, y1, span_id).
"""
x0 = min(elem, key=lambda item: item.x).x
x1 = max(elem, key=lambda item: item.x_end).x_end
y0 = min(elem, key=lambda item: item.y).y
y1 = max(elem, key=lambda item: item.y).y
span = elem[0].span_id
return ElementDimension(x0=x0, x1=x1, y0=y0, y1=y1, span_id=span)
def intersect(bbox1: ElementDimension, bbox2: ElementDimension) -> bool:
"""Check if two bounding boxes intersect.
Args:
bbox1 (ElementDimension): Bounding box 1. (x0, y0, x1, y1)
bbox2 (ElementDimension): Bounding box 2. (x0, y0, x1, y1)
Returns:
bool: True if the bounding boxes intersect, else False.
"""
return not (bbox2.x0 > bbox1.x1 or bbox2.x1 < bbox1.x0 or bbox2.y0 > bbox1.y1 or bbox2.y1 < bbox1.y0)
def to_text(el: list[HotCharacter]) -> str:
"""Convert a list of HotCharacter instances to text.
Args:
el (list): List of HotCharacter instances.
Returns:
str: The text.
"""
return "".join(char.value for char in el)
+100
View File
@@ -0,0 +1,100 @@
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta:__legacy__"
[project]
name="hotpdf"
version="0.5.3"
authors = [
{name = "Krishnasis Mandal", email = "krishnasis@hotmail.com"}]
maintainers = [
{name = "Alex Ptakhin" , email = "alex.ptakhin@prestatech.com"},
{name = "Izel Odabasi" , email = "izel.odabasi@prestatech.com"},
{name = "Mattia Callegari" , email = "callegari.mattia@protonmail.com"}]
description = "Fast PDF Data Extraction library"
readme = "README.md"
license = {file = "LICENSE"}
requires-python = ">=3.9"
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.9",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: General",
"Topic :: Text Processing :: Indexing",
"Topic :: Text Processing :: Linguistic",
"Topic :: Utilities",
"Operating System :: OS Independent",
]
keywords = [
"pdf",
"data extraction",
"text extraction",
"hotpdf",
"pdfminer",
"pdfquery"
]
dependencies = [
"pdfminer.six>=20231228",
]
[tool.setuptools]
include-package-data = false
[tool.setuptools.packages.find]
include = ["hotpdf*"]
exclude = ["docs*", "tests*"]
[project.optional-dependencies]
dev = ["pytest", "pytest-cov", "pytest-xdist", "pylint", "mypy", "typing-extensions", "pre-commit", "ruff"]
docs = ["pdfminer.six"]
[tool.ruff]
indent-width = 4
line-length = 120
select = [
# pycodestyle
"E", "W",
# Pyflakes
"F",
# pyupgrade
"UP",
# flake8-bugbear
"B",
# flake8-simplify
"SIM",
# isort
"I",
# MaccaBe
"C901",
# Pep8-naming
#"N", # TODO: enable
]
fix = true
fixable = ["ALL"]
exclude = ["docs"]
preview = true
[tool.ruff.mccabe]
max-complexity = 10
[tool.mypy]
warn_unused_configs = true
files = "hotpdf"
ignore_missing_imports = true
check_untyped_defs = true
explicit_package_bases = true
warn_unreachable = true
warn_redundant_casts = true
strict = true
[tool.pytest.ini_options]
log_cli=true
log_level="NOTSET"
View File
+57
View File
@@ -0,0 +1,57 @@
import pytest
@pytest.fixture()
def valid_file_name():
return "tests/resources/PDF.pdf"
@pytest.fixture()
def blank_file_name():
return "tests/resources/blank.pdf"
@pytest.fixture()
def multiple_pages_file_name():
return "tests/resources/20pages.pdf"
@pytest.fixture()
def non_existent_file_name():
return "non_existent_file.pdf"
@pytest.fixture()
def locked_file_name():
return "tests/resources/PDF_locked.pdf"
@pytest.fixture()
def invalid_file_name():
return "tests/resources/invalid_file.txt"
@pytest.fixture()
def bible_file_name():
return "tests/resources/bible.pdf"
@pytest.fixture()
def mock_hotpdf_bank_file_name():
return "tests/resources/hotpdf_bank.pdf"
@pytest.fixture()
def duplicate_span_file_name():
return "tests/resources/dup_span.pdf"
@pytest.fixture
def document_lt_figure_file_name():
# File sourced from: https://github.com/druskacik/ltfigure-pdfminer
return "tests/resources/doc_lt_figure.pdf"
@pytest.fixture()
def variations_simple_file_name():
return "tests/resources/test_variations_simple.pdf"
Binary file not shown.
Binary file not shown.
Binary file not shown.