receipt-ocr 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: receipt-ocr
3
+ Version: 0.1.0
4
+ Summary: A package for extracting structured data from receipts.
5
+ Project-URL: Homepage, https://github.com/bhimrazy/receipt-ocr
6
+ Project-URL: Bug Tracker, https://github.com/bhimrazy/receipt-ocr/issues
7
+ Project-URL: Documentation, https://github.com/bhimrazy/receipt-ocr
8
+ Project-URL: Source Code, https://github.com/bhimrazy/receipt-ocr
9
+ Project-URL: Download, https://github.com/bhimrazy/receipt-ocr
10
+ Author-email: Bhimraj Yadav <bhimrajyadav977@gmail.com>
11
+ License: MIT License
12
+
13
+ Copyright (c) 2025 Bhimraj Yadav
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+ License-File: LICENSE
33
+ Keywords: llm,ocr,receipts,tesseract
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Environment :: Console
36
+ Classifier: Intended Audience :: Developers
37
+ Classifier: License :: OSI Approved :: MIT License
38
+ Classifier: Natural Language :: English
39
+ Classifier: Operating System :: OS Independent
40
+ Classifier: Programming Language :: Python :: 3
41
+ Classifier: Programming Language :: Python :: 3.9
42
+ Classifier: Programming Language :: Python :: 3.10
43
+ Classifier: Programming Language :: Python :: 3.11
44
+ Classifier: Programming Language :: Python :: 3.12
45
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
46
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
47
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
48
+ Requires-Python: >=3.9
49
+ Requires-Dist: openai
50
+ Requires-Dist: pillow
51
+ Requires-Dist: python-dotenv
52
+ Description-Content-Type: text/markdown
53
+
54
+ # Receipt OCR Engine
55
+
56
+ This repository hosts a script and a Docker-compose setup for performing Optical Character Recognition (OCR) on receipt images.
57
+
58
+ ![image](https://github.com/bhimrazy/receipt-ocr/assets/46085301/305df68d-50d8-41d4-81d0-9324966fb6c9)
59
+
60
+ ## Star History
61
+
62
+ <a href="https://star-history.com/#bhimrazy/receipt-ocr&Date">
63
+ <picture>
64
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=bhimrazy/receipt-ocr&type=Date&theme=dark" />
65
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=bhimrazy/receipt-ocr&type=Date" />
66
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=bhimrazy/receipt-ocr&type=Date" />
67
+ </picture>
68
+ </a>
69
+
70
+ ## Prerequisites
71
+
72
+ - Python 3.x
73
+ - Docker
74
+ - Docker-compose
75
+
76
+ ## Installation
77
+
78
+ ### Clone the repository
79
+
80
+ ```bash
81
+ git clone https://github.com/bhimrazy/receipt-ocr.git
82
+ cd receipt-ocr
83
+ ```
84
+
85
+ ### Set up Python environment (if not using Docker)
86
+ - Install [tesseract](https://tesseract-ocr.github.io/tessdoc/Installation.html)
87
+
88
+ ```bash
89
+ # Create and activate a virtual environment (optional but recommended)
90
+ python -m venv venv
91
+ source venv/bin/activate # For Windows, use venv\Scripts\activate
92
+
93
+ # Install dependencies
94
+ pip install -r requirements.txt
95
+ ```
96
+
97
+ ## Usage
98
+
99
+ ### Running the script locally
100
+
101
+ #### `main.py`
102
+
103
+ The `main.py` script performs OCR on an input image of a receipt.
104
+
105
+ ```bash
106
+ python main.py -i images/receipt.jpg
107
+ ```
108
+
109
+ Replace `images/receipt.jpg` with the path to your receipt image.
110
+ >Please ensure that the image is well-lit and that the edges of the receipt are clearly visible and detectable within the image.
111
+ <img src="https://github.com/bhimrazy/receipt-ocr/assets/46085301/2ea009f0-9e15-42b2-9f15-063a8ec169f1" alt="Receipt Image" width="300" height="400">
112
+
113
+
114
+ ### Using Docker-compose
115
+
116
+ The repository includes a Docker-compose setup for running the OCR engine as a service.
117
+
118
+ ```bash
119
+ docker-compose up
120
+ ```
121
+
122
+ Once the service is up and running, you can perform OCR on receipt images by sending a POST request to `http://localhost:8000/ocr/` with the image file.
123
+
124
+ ## API Endpoint
125
+
126
+ The OCR functionality can be accessed via a FastAPI endpoint:
127
+
128
+ - **POST** `/ocr/`: Upload a receipt image file to perform OCR. The response will contain the extracted text from the receipt.
129
+
130
+ Example usage with cURL:
131
+
132
+ ```bash
133
+ curl -X 'POST' \
134
+ 'http://localhost:8000/ocr/' \
135
+ -H 'accept: application/json' \
136
+ -H 'Content-Type: multipart/form-data' \
137
+ -F 'file=@images/paper-cash-sell-receipt-vector-23876532.jpg;type=image/jpeg'
138
+ ```
139
+
140
+ ## Using Gemini
141
+ - Gemini Docs:https://ai.google.dev/tutorials/python_quickstart
142
+ - LinkedIn Post: https://www.linkedin.com/feed/update/urn:li:activity:7145860319150505984/
143
+
144
+ ![image](https://github.com/bhimrazy/receipt-ocr/assets/46085301/ee4a0c82-f134-4a19-a275-93a59c7503b8)
145
+
146
+
147
+ ## License
148
+
149
+ This project is licensed under the terms of the MIT license.
150
+
151
+ ## References
152
+ - [Automatically OCR’ing Receipts and Scans](https://pyimagesearch.com/2021/10/27/automatically-ocring-receipts-and-scans/)
153
+
154
+
@@ -0,0 +1,11 @@
1
+ src/receipt_ocr/__about__.py,sha256=JiuulFAhKiGdiLlzpmDNzxQworwYN36usDdY_HrWAJg,447
2
+ src/receipt_ocr/__init__.py,sha256=nTXoT7OD7yo_j08DAsMF_SwbrcInLz6sNcmxRozErfE,189
3
+ src/receipt_ocr/cli.py,sha256=QtxZisXzlXEyIDMhCXUcVWwb5Hjb5uUYGmQ7f1Fgsvc,2525
4
+ src/receipt_ocr/parsers.py,sha256=IZriFyabV_YHSguUv72g7zdaBeiFPm7g7uoUsF7tk5Y,718
5
+ src/receipt_ocr/prompts.py,sha256=FBFxnxzlwqcZcDZ1pDhYmm5Ctculu12ldd5PR6VhPaA,861
6
+ src/receipt_ocr/providers.py,sha256=BtWMbu6CeJdILcQN2tKLizvPkYY8BV6XOdzpaBAfE3M,2098
7
+ receipt_ocr-0.1.0.dist-info/METADATA,sha256=gesai8yaMde8J8sWhHBa19yKXu7OBC_VOzyRxX6E5P8,5730
8
+ receipt_ocr-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ receipt_ocr-0.1.0.dist-info/entry_points.txt,sha256=DH35VJcOutisJ4FWujHU0XMrXVH0LDEdNQXLNwzn9ls,53
10
+ receipt_ocr-0.1.0.dist-info/licenses/LICENSE,sha256=aUC5PJ0cU7_TKITWsk1r5CFZJQ8s1di8pZlMG3sNUao,1069
11
+ receipt_ocr-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ receipt-ocr = receipt_ocr.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bhimraj Yadav
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ __version__ = "0.1.0"
2
+ __docs__ = "A package for extracting structured data from receipts."
3
+ __author__ = "Bhimraj Yadav"
4
+ __author_email__ = "bhimrajyadav977@gmail.com"
5
+ __license__ = "MIT"
6
+ __copyright__ = "Copyright (c) 2025 Bhimraj Yadav"
7
+ __homepage__ = "https://github.com/bhimrazy/receipt-ocr"
8
+
9
+ __all__ = [
10
+ "__author__",
11
+ "__author_email__",
12
+ "__copyright__",
13
+ "__docs__",
14
+ "__homepage__",
15
+ "__license__",
16
+ "__version__",
17
+ ]
@@ -0,0 +1,9 @@
1
+ from .cli import ReceiptProcessor
2
+ from .parsers import ReceiptParser
3
+ from .providers import OpenAIProvider
4
+
5
+ __all__ = [
6
+ "ReceiptProcessor",
7
+ "OpenAIProvider",
8
+ "ReceiptParser",
9
+ ]
src/receipt_ocr/cli.py ADDED
@@ -0,0 +1,89 @@
1
+ import argparse
2
+ import os
3
+ import json
4
+ from .providers import OpenAIProvider
5
+ from .parsers import ReceiptParser
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+
11
+ class ReceiptProcessor:
12
+ """
13
+ Process a receipt image and return a structured JSON object.
14
+ """
15
+
16
+ def __init__(self, provider, parser):
17
+ """
18
+ Initialize the receipt processor.
19
+ """
20
+ self.provider = provider
21
+ self.parser = parser
22
+
23
+ def process_receipt(self, image_path: str, json_schema: dict, model: str) -> dict:
24
+ """
25
+ Process a receipt image and return a structured JSON object.
26
+ """
27
+ response = self.provider.get_response(image_path, json_schema, model)
28
+ return self.parser.parse(response)
29
+
30
+
31
+ def main():
32
+ """
33
+ Main function for the CLI.
34
+ """
35
+ parser = argparse.ArgumentParser(
36
+ description="Extract information from a receipt image."
37
+ )
38
+ parser.add_argument("image_path", type=str, help="The path to the receipt image.")
39
+ parser.add_argument(
40
+ "--schema_path", type=str, help="The path to a custom JSON schema file."
41
+ )
42
+ parser.add_argument(
43
+ "--model",
44
+ type=str,
45
+ default="gpt-4-vision-preview",
46
+ help="The model to use for the LLM.",
47
+ )
48
+ parser.add_argument("--api_key", type=str, help="The API key for the LLM provider.")
49
+ parser.add_argument(
50
+ "--base_url", type=str, help="The base URL for the LLM provider."
51
+ )
52
+ args = parser.parse_args()
53
+
54
+ # Load the JSON schema
55
+ if args.schema_path:
56
+ with open(args.schema_path, "r") as f:
57
+ json_schema = json.load(f)
58
+ else:
59
+ json_schema = {
60
+ "merchant_name": "string",
61
+ "merchant_address": "string",
62
+ "transaction_date": "string",
63
+ "transaction_time": "string",
64
+ "total_amount": "number",
65
+ "line_items": [
66
+ {
67
+ "item_name": "string",
68
+ "item_quantity": "number",
69
+ "item_price": "number",
70
+ }
71
+ ],
72
+ }
73
+
74
+ # Initialize the provider and parser
75
+ provider = OpenAIProvider(api_key=args.api_key, base_url=args.base_url)
76
+ parser = ReceiptParser()
77
+
78
+ # Initialize the processor
79
+ processor = ReceiptProcessor(provider, parser)
80
+
81
+ # Process the receipt
82
+ result = processor.process_receipt(args.image_path, json_schema, args.model)
83
+
84
+ # Print the result
85
+ print(json.dumps(result, indent=4))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,23 @@
1
+ import json
2
+
3
+
4
+ class ReceiptParser:
5
+ """
6
+ Parser for the LLM's response.
7
+ """
8
+
9
+ def parse(self, response: str) -> dict:
10
+ """
11
+ Parse the LLM's response and return a JSON object.
12
+ """
13
+ try:
14
+ # The response is often wrapped in a code block
15
+ response = response.strip()
16
+ if response.startswith("```json"):
17
+ response = response[7:-4]
18
+ elif response.startswith("```"):
19
+ response = response[3:-3]
20
+ return json.loads(response)
21
+ except json.JSONDecodeError:
22
+ # Handle the case where the response is not valid JSON
23
+ return {"error": "The LLM's response was not valid JSON."}
@@ -0,0 +1,35 @@
1
+ SYSTEM_PROMPT = """
2
+ You are a world-class receipt processing expert. Your task is to accurately extract information from a receipt image and provide it in a structured JSON format.
3
+
4
+ Here is an example of a desired JSON output:
5
+
6
+ ```json
7
+ {{
8
+ "merchant_name": "Example Store",
9
+ "merchant_address": "123 Main St, Anytown, USA 12345",
10
+ "transaction_date": "2023-01-01",
11
+ "transaction_time": "12:34:56",
12
+ "total_amount": 75.50,
13
+ "line_items": [
14
+ {{
15
+ "item_name": "Item 1",
16
+ "item_quantity": 2,
17
+ "item_price": 20.00
18
+ }},
19
+ {{
20
+ "item_name": "Item 2",
21
+ "item_quantity": 1,
22
+ "item_price": 35.50
23
+ }}
24
+ ]
25
+ }}
26
+ ```
27
+
28
+ Please extract the information from the receipt image and provide it in the following JSON schema:
29
+
30
+ ```json
31
+ {{json_schema_content}}
32
+ ```
33
+ """
34
+
35
+ USER_PROMPT = "Please extract the information from this receipt image."
@@ -0,0 +1,73 @@
1
+ import os
2
+ from abc import ABC, abstractmethod
3
+ from openai import OpenAI
4
+ from PIL import Image
5
+ import base64
6
+ import io
7
+ import json
8
+ from .prompts import SYSTEM_PROMPT, USER_PROMPT
9
+
10
+
11
+ class LLMProvider(ABC):
12
+ """
13
+ Abstract base class for LLM providers.
14
+ """
15
+
16
+ @abstractmethod
17
+ def get_response(self, image_path: str, json_schema: dict, model: str) -> str:
18
+ """
19
+ Get the response from the LLM provider.
20
+ """
21
+ pass
22
+
23
+
24
+ class OpenAIProvider(LLMProvider):
25
+ """
26
+ LLM provider for OpenAI-compatible APIs.
27
+ """
28
+
29
+ def __init__(self, api_key: str = None, base_url: str = None):
30
+ """
31
+ Initialize the OpenAI provider.
32
+ """
33
+ self.api_key = api_key or os.getenv("OPENAI_API_KEY")
34
+ self.base_url = base_url or os.getenv("OPENAI_BASE_URL")
35
+ self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
36
+
37
+ def get_response(self, image_path: str, json_schema: dict, model: str) -> str:
38
+ """
39
+ Get the response from the OpenAI API.
40
+ """
41
+ # Load the image
42
+ image = Image.open(image_path)
43
+
44
+ # Convert the image to base64
45
+ buffered = io.BytesIO()
46
+ image.save(buffered, format="PNG")
47
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
48
+
49
+ # Create the system prompt
50
+ system_prompt = SYSTEM_PROMPT
51
+
52
+ response = self.client.chat.completions.create(
53
+ model=model,
54
+ response_format={"type": "json_object"},
55
+ messages=[
56
+ {
57
+ "role": "system",
58
+ "content": system_prompt,
59
+ },
60
+ {
61
+ "role": "user",
62
+ "content": [
63
+ {"type": "text", "text": USER_PROMPT},
64
+ {
65
+ "type": "image_url",
66
+ "image_url": {"url": f"data:image/png;base64,{img_str}"},
67
+ },
68
+ ],
69
+ },
70
+ ],
71
+ )
72
+
73
+ return response.choices[0].message.content