Skip to content

Commit

Permalink
Initial parser release
Browse files Browse the repository at this point in the history
  • Loading branch information
mirzadelic committed Apr 8, 2024
1 parent a309774 commit a6c759e
Show file tree
Hide file tree
Showing 12 changed files with 1,501 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Tests
"on":
push:
branches:
- "*"
jobs:
tests:
runs-on: ubuntu-22.04
strategy:
max-parallel: 2
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11"]
steps:
- uses: actions/checkout@v4
- name: "Setup Python ${{ matrix.python-version }}"
uses: actions/setup-python@v5
with:
python-version: "${{ matrix.python-version }}"
cache: pip
cache-dependency-path: "**/requirements.txt"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run Tests
run: |
pytest .
164 changes: 164 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# 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

# 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/
.DS_Store
.ruff_cache/
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# SR Invoice Parser

[![build-status-image]][build-status]

SR Invoice Parser is a small library that is parsing invoices and extracting relevant information.
It is designed to work with invoices from the Tax Administration of the Republic of Serbia (Poreska uprava Republike Srbije).

- https://purs.gov.rs/
- https://suf.purs.gov.rs/

QR code gives a URL to the invoice web page, and this parser extracts the relevant information from the web page, like a crawler.

## Installation

To install SR Invoice Parser, follow these steps:

pip install sr-invoice-parser

## Usage

The `InvoiceParser` class is the entry point for using the parser.

### Methods

- `get_data()` - Extracts all the data from the invoice and returns it as a dictionary
- `get_company_name()` - Extracts the company name.
- `get_company_tin()` - Extracts the company's tax identification number/PFR.
- `get_total_amount()` - Extracts the total amount of the invoice.
- `get_dt()` - Extracts the date and time of the invoice and converts it to UTC as a datetime object.
- `get_invoice_number()` - Extracts the invoice number.
- `get_invoice_text()` - Extracts the full text of the invoice with QR code base64.
- `get_items()` - Extracts items details from the invoice. This is array of dictionaries with keys: `name`, `quantity`, `price`, `total_price`.

Here's a basic example of how to use it:

```python
from sr_invoice_parser import InvoiceParser

parser = InvoiceParser(url="https://suf.purs.gov.rs/v/?vl=...")
# or
parser = InvoiceParser(html_text="<HTML source code of invoice web page>")

parser.data()

parser.get_company_name()
parser.get_company_tin()
parser.get_total_amount()
parser.get_dt()
parser.get_invoice_number()
parser.get_invoice_text()
parser.get_items()

```

## Example response data

```python
{
"company_name": "Company Name",
"company_tin": "123456789",
"invoice_number": "QWERTYU1-QWERTYU1-12345",
"invoice_datetime": datetime.datetime(2021, 1, 1, 0, 0, tzinfo=datetime.timezone.utc),
"invoice_total_amount": 123.45,
"invoice_text": "============ ФИСКАЛНИ РАЧУН ============.....",
"invoice_items": [
{
"name": "Item 1",
"quantity": 1,
"price": 123.45,
"total_price": 123.45
}
]
}
```

Check the [test_parser.py](/tests/test_parser.py) file for more examples.

## Handling Exceptions

The module has custom exceptions for handling various error scenarios:

- `ParserParseException` - Raised when any error occurs during parsing the HTML content.
- `ParserRequestException` - Raised for errors related to fetching HTML content.

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

If you have any questions, please contact us via email: [[email protected]](mailto:[email protected]?subject=[GitHub]%20sr-invoice-parser%20Question)

## License

This project is licensed under the [MIT License](/LICENSE).

[build-status-image]: https://github.com/Innovigo/sr-invoice-parser/actions/workflows/tests.yaml/badge.svg
[build-status]: https://github.com/Innovigo/sr-invoice-parser/actions/workflows/tests.yaml
Empty file added conftest.py
Empty file.
31 changes: 31 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[build-system]
requires = ["flit_core>=3.9.0"]
build-backend = "flit_core.buildapi"

[project]
name = "sr-invoice-parser"
dynamic = ["version", "description"]
authors = [
{ name="Innovigo", email="[email protected]" },
]
readme = "README.md"
license = {text = "MIT"}

requires-python = ">=3.8"
dependencies = [
"pytz>=2021.1",
"requests>=2.21.0",
"parsel>=1.7.0",
"srtools>=0.1.13",
]
classifiers = [
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Libraries :: Python Modules",
]

[project.urls]
Home = "https://github.com/Innovigo/sr-invoice-parser"
Source = "https://github.com/Innovigo/sr-invoice-parser"
Issues = "https://github.com/Innovigo/sr-invoice-parser/issues"
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pytz>=2021.1
requests>=2.21.0
parsel>=1.7.0
srtools>=0.1.13
flit-core>=3.9.0
ruff
pytest
14 changes: 14 additions & 0 deletions sr_invoice_parser/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""SR Invoice Parser is a small library(crawler) that is parsing invoices and extracting relevant information from URL. For Serbian market."""

__title__ = "sr_invoice_parser"
__author__ = "Innovigo"
__website__ = "https://wwwinnovigo.co/"
__email__ = "[email protected]"
__version__ = "0.0.1"

VERSION = __version__

from .exceptions import ParserParseException, ParserRequestException # noqa: E402
from .parser import InvoiceParser # noqa: E402

__all__ = ["InvoiceParser", "ParserRequestException", "ParserParseException"]
19 changes: 19 additions & 0 deletions sr_invoice_parser/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import functools

from .exceptions import ParserParseException


def handle_exception():
def wrapper(function):
@functools.wraps(function)
def inner(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e:
raise ParserParseException(
f"Failed to parse the HTML content in '{function.__name__}': {e}"
)

return inner

return wrapper
6 changes: 6 additions & 0 deletions sr_invoice_parser/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class ParserRequestException(Exception):
pass


class ParserParseException(Exception):
pass
Loading

0 comments on commit a6c759e

Please sign in to comment.