aiXpert commited on
Commit
e3cb0b8
1 Parent(s): 9013e02
AI-Powered_Receipt_Bot.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from utils import st_def
3
+ st.set_page_config('AI-Powred 👋 Receipt Extract', page_icon="🚀",)
4
+ st_def.st_logo('Receipt Extract')
5
+ st.image("./images/receipttextextraction.png")
6
+
7
+ st.markdown("""
8
+ #### 🚀 Template-Based OCR (Optical Character Recognition) 🍨
9
+ Description: Using pre-defined templates to extract text from receipts based on the expected layout and structure.
10
+
11
+ **Limitations**:
12
+ — Relies on consistent and standardized receipt formats, which is rarely the case in real-world scenarios.
13
+ — Struggles with variations in receipt layouts, such as different fonts, spacing, or orientations.
14
+ — Requires creating and maintaining a large number of templates to accommodate different receipt formats.
15
+ — Limited flexibility and adaptability to handle new or unseen receipt formats.
16
+
17
+ ### 📄Rule-Based Text Extraction📚:
18
+ Description: Defining a set of rules and regular expressions to extract specific information from receipts based on patterns and keywords.
19
+ **Limitations**:
20
+ — Requires extensive domain knowledge and manual effort to define and maintain the rules.
21
+ — Rules can become complex and difficult to manage as the variety of receipt formats increases.
22
+ — Struggles with handling variations in terminology, abbreviations, or language used in receipts.
23
+ — Limited scalability and adaptability to new receipt formats or changes in existing ones.
24
+
25
+ ### 🔍 Python Libraries for Traditional Machine Learning Approaches📰
26
+ `scikit-learn (sklearn)`: scikit-learn is a widely used Python library for machine learning tasks.
27
+ It provides a comprehensive set of tools for data preprocessing, feature extraction, model training, and evaluation.
28
+ scikit-learn offers various machine learning algorithms, including Support Vector Machines (SVM), Random Forests, and more.
29
+
30
+ `NLTK` (Natural Language Toolkit):NLTK is a popular Python library for natural language processing (NLP) tasks. It provides utilities for text preprocessing, tokenization, stemming, and feature extraction.
31
+ NLTK can be used in conjunction with scikit-learn for text-based machine learning tasks.
32
+
33
+ `spaCy`: spaCy is another powerful NLP library for Python.
34
+ It offers advanced features for text preprocessing, named entity recognition, part-of-speech tagging, and more.
35
+ spaCy can be used to extract additional features from the receipt text to enhance the machine learning models.
36
+
37
+ **Limitations of Traditional Approaches**:
38
+ The traditional approaches to receipt text extraction suffer from several limitations that hinder their effectiveness and scalability:
39
+
40
+ 1. Lack of Flexibility: Traditional approaches struggle to handle the wide variety of receipt formats and layouts encountered in real-world scenarios. They often rely on fixed templates or rules, making them inflexible and difficult to adapt to new or unseen receipt formats.
41
+ 2. Manual Effort and Domain Knowledge: Traditional approaches often require significant manual effort and domain expertise to define templates, rules, or features for text extraction. This process can be time-consuming and requires continuous updates and maintenance as receipt formats evolve.
42
+ 3. Limited Scalability: As the volume and variety of receipts increase, traditional approaches face challenges in scaling efficiently. Manual data entry becomes impractical, and rule-based systems become complex and difficult to manage.
43
+ 4. Sensitivity to Variations: Traditional approaches are sensitive to variations in receipt layouts, fonts, spacing, or terminology. They may struggle to accurately extract information when faced with inconsistencies or deviations from expected patterns.
44
+ 5. Lack of Contextual Understanding: Traditional approaches often lack the ability to understand the contextual meaning and relationships between different elements in a receipt. They rely on predefined patterns and fail to capture the nuances and semantics of the text.
45
+ 6. Limited Language Support: Traditional approaches may have limited support for multiple languages or may require separate models or rules for each language, making it challenging to process receipts from different regions or countries.
46
+
47
+ # 🍨 Text Extraction App Using Streamlit and OpenAI Vision
48
+ """)
49
+ st.image("./images/zhang.gif")
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,13 +1,16 @@
1
- ---
2
- title: Receiptbot
3
- emoji: 🔥
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: streamlit
7
- sdk_version: 1.33.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
1
+ # AI-powered Receipt Bot
2
+
3
+ The application is designed to process electronic and scanned receipts.
4
+ It sendsthese images to an LLM model, which extracts detailed information from the receipts.
5
+ Then, it stores this information in a database.
6
+
7
+ The app has two main parts: uploading and processing receipt images, and displaying the extracted data.
8
+
9
+ The `process_image(image)` function takes an uploaded image, encodes it, and then sends a request to OpenAI’s API with the encoded image and the instructions on what information to extract.
10
+
11
+ The response from OpenAI’s API, which includes the extracted data in JSON format, is then processed.
12
+
13
+ The function extracts the relevant data from this JSON and inserts it into the MySQL database.
14
+
15
+ The database insertion involves two steps: first, inserting the receipt headerinformation, and then inserting details about each line item on the receipt.
16
+
Receipt Extract.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
3
+ import requests
4
+ import mysql.connector
5
+ import json
6
+ from datetime import datetime
7
+
8
+ # Streamlit app title
9
+ st.title("Receipt Extractor")
10
+
11
+ # OpenAI API Key
12
+ api_key = "Your Password"
13
+
14
+ # Database connection parameters
15
+ db_config = {
16
+ 'host': 'localhost',
17
+ 'user': 'root',
18
+ 'password': 'Your Password',
19
+ 'database': 'receipts'
20
+ }
21
+
22
+ var_for = """Given the receipt image provided, extract all relevant information and structure the output as detailed JSON that matches the database schema for storing receipt headers and line items. The receipt headers should include store name, slogan, address, store manager, phone number, transaction ID, date, time, cashier, subtotal, sales tax, total, gift card, charged amount, card type, authorization code, chip read, AID, issuer, policy ID, expiration date, survey message, survey website, user ID, password, and eligibility note. The line items should include SKU, description, details, and price for each item on the receipt. Exclude any sensitive information from the output. Format the JSON as follows:
23
+
24
+ {
25
+ "receipt_headers": {
26
+ "store_name": "",
27
+ "slogan": "",
28
+ "address": "",
29
+ "store_manager": "",
30
+ "phone_number": "",
31
+ "transaction_id": "",+
32
+ "date": "",
33
+ "time": "",
34
+ "cashier": "",
35
+ "subtotal": 0,
36
+ "sales_tax": 0,
37
+ "total": 0,
38
+ "gift_card": 0,
39
+ "charged_amount": 0,
40
+ "card_type": "",
41
+ "auth_code": "",
42
+ "chip_read": "",
43
+ "aid": "",
44
+ "issuer": "",
45
+ "policy_id": "",
46
+ "expiration_date": "",
47
+ "survey_message": "",
48
+ "survey_website": "",
49
+ "user_id": "",
50
+ "password": "",
51
+ "eligibility_note": ""
52
+ },
53
+ "line_items": [
54
+ {
55
+ "sku": "",
56
+ "description": "",
57
+ "details": "",
58
+ "price": 0
59
+ }
60
+ ]
61
+ }"""
62
+
63
+ # Function to encode the image
64
+ def encode_image(image):
65
+ return base64.b64encode(image.read()).decode('utf-8')
66
+
67
+ # Function to process the uploaded image and update the database
68
+ def process_image(image):
69
+ base64_image = encode_image(image)
70
+
71
+ headers = {
72
+ "Content-Type": "application/json",
73
+ "Authorization": f"Bearer {api_key}"
74
+ }
75
+
76
+ payload = {
77
+ "model": "gpt-4-vision-preview",
78
+ "messages": [
79
+ {
80
+ "role": "user",
81
+ "content": [
82
+ {
83
+ "type": "text",
84
+ "text": var_for
85
+ },
86
+ {
87
+ "type": "image_url",
88
+ "image_url": {
89
+ "url": f"data:image/jpeg;base64,{base64_image}"
90
+ }
91
+ }
92
+ ]
93
+ }
94
+ ],
95
+ "max_tokens": 2048
96
+ }
97
+
98
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
99
+ response_json = response.json()
100
+ receipt_data_str = response_json['choices'][0]['message']['content']
101
+
102
+ # Find the JSON string within the extracted content
103
+ receipt_data_json_str = receipt_data_str.split('```json')[1].split('```')[0].strip()
104
+ receipt_data = json.loads(receipt_data_json_str)
105
+
106
+ # Connect to the database
107
+ conn = mysql.connector.connect(**db_config)
108
+ cursor = conn.cursor()
109
+
110
+ # Insert into receipt_headers
111
+ header_insert_query = """
112
+ INSERT INTO receipt_headers (store_name, slogan, address, store_manager, phone_number, transaction_id, date, time, cashier, subtotal, sales_tax, total, gift_card, charged_amount, card_type, auth_code, chip_read, aid, issuer, policy_id, expiration_date, survey_message, survey_website, user_id, password, eligibility_note)
113
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
114
+ """
115
+
116
+ header_info = receipt_data['receipt_headers']
117
+ line_items = receipt_data['line_items']
118
+
119
+ # Format date, time, and expiration_date
120
+ formatted_date = datetime.strptime(header_info['date'], '%m/%d/%y').strftime('%Y-%m-%d')
121
+ formatted_time = datetime.strptime(header_info['time'], '%I:%M %p').strftime('%H:%M:%S')
122
+ formatted_expiration_date = datetime.strptime(header_info['expiration_date'], '%m/%d/%Y').strftime('%Y-%m-%d')
123
+
124
+ # Prepare header values
125
+ header_values = (
126
+ header_info['store_name'],
127
+ header_info['slogan'],
128
+ header_info['address'],
129
+ header_info['store_manager'],
130
+ header_info['phone_number'],
131
+ header_info['transaction_id'],
132
+ formatted_date,
133
+ formatted_time,
134
+ header_info['cashier'],
135
+ header_info['subtotal'],
136
+ header_info['sales_tax'],
137
+ header_info['total'],
138
+ header_info['gift_card'],
139
+ header_info['charged_amount'],
140
+ header_info['card_type'],
141
+ header_info['auth_code'],
142
+ header_info['chip_read'],
143
+ header_info['aid'],
144
+ header_info['issuer'],
145
+ header_info['policy_id'],
146
+ formatted_expiration_date,
147
+ header_info['survey_message'],
148
+ header_info['survey_website'],
149
+ header_info['user_id'],
150
+ header_info['password'],
151
+ header_info['eligibility_note']
152
+ )
153
+
154
+ # Insert header values
155
+ cursor.execute(header_insert_query, header_values)
156
+ receipt_id = cursor.lastrowid
157
+
158
+ # Prepare and insert line items
159
+ line_item_insert_query = """
160
+ INSERT INTO line_items (receipt_id, sku, description, details, price)
161
+ VALUES (%s, %s, %s, %s, %s)
162
+ """
163
+
164
+ for item in line_items:
165
+ price = float(item['price'])
166
+ line_item_values = (
167
+ receipt_id,
168
+ item['sku'],
169
+ item['description'],
170
+ item.get('details', ''),
171
+ price
172
+ )
173
+
174
+ cursor.execute(line_item_insert_query, line_item_values)
175
+
176
+ # Commit and close the connection
177
+ conn.commit()
178
+ cursor.close()
179
+ conn.close()
180
+
181
+ return receipt_data
182
+
183
+ # Streamlit tabs
184
+ tab1, tab2 = st.tabs(["Upload Receipt", "Display the Data"])
185
+
186
+ with tab1:
187
+ st.header("Upload Receipt")
188
+ uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])
189
+
190
+ if uploaded_file is not None:
191
+ # Display the uploaded image
192
+ st.image(uploaded_file, caption='Uploaded Receipt', use_column_width=True)
193
+
194
+ # Process the uploaded image
195
+ receipt_data = process_image(uploaded_file)
196
+
197
+ # Display success message
198
+ st.success("Message received successfully from the LLM.")
199
+
200
+ # Display the JSON output
201
+ st.json(receipt_data)
202
+
203
+
204
+ with tab2:
205
+ st.header("Display the Data")
206
+
207
+ # Connect to the database
208
+ conn = mysql.connector.connect(**db_config)
209
+ cursor = conn.cursor()
210
+
211
+ # Fetch all records from the receipt_headers table, excluding the time column
212
+ cursor.execute("SELECT store_name, slogan, address, store_manager, phone_number, transaction_id, date, cashier, subtotal, sales_tax, total, gift_card, charged_amount, card_type, auth_code, chip_read, aid, issuer, policy_id, expiration_date, survey_message, survey_website, user_id, password, eligibility_note FROM receipt_headers;")
213
+ headers = cursor.fetchall()
214
+
215
+ # Display the headers in a table
216
+ st.subheader("Receipt Headers")
217
+ st.table(headers)
218
+
219
+ # Fetch and display all records from the line_items table
220
+ st.subheader("Line Items")
221
+ cursor.execute("SELECT * FROM line_items;")
222
+ items = cursor.fetchall()
223
+ st.table(items)
224
+
225
+ # Close the cursor and the connection
226
+ cursor.close()
227
+ conn.close()
data/invoice_Aaron Hawkins_38460.jpg ADDED
data/invoice_Aaron Hawkins_38460.pdf ADDED
Binary file (18.8 kB). View file
 
data/scanned_sample.png ADDED
data/starbucks_20221210_008_Page_1.jpg ADDED
data/starbucks_20221210_008_Page_2.jpg ADDED
images/receipttextextraction.png ADDED
images/sslogo.png ADDED
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ build-essential
2
+ pkg-config
3
+ default-libmysqlclient-dev
pages/1_📊Electronic_Receipt (e-Receipt).py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from utils import st_def, ai
3
+ import openai, PyPDF2, os, time, pandas as pd
4
+
5
+ st_def.st_logo(title='👋 e-Recepit Extract')
6
+ tab1, tab2 = st.tabs(["Upload Receipt", "Display the Data"])
7
+ page_text = [] #array for page
8
+
9
+ with tab1:
10
+ st.markdown('An electronic receipt, commonly known as an e-receipt, is a digital version of a traditional paper receipt that is generated and delivered electronically. Instead of a tangible piece of paper, e-receipts are sent via electronic channels, such as email or mobile applications, as proof of a transaction. They include the same transaction information as paper receipts, such as the date, time, and items purchased.')
11
+ st.image("./data/invoice_Aaron Hawkins_38460.jpg")
12
+ pdf1 = st.file_uploader('Upload your e-Receipt: ', type='pdf')
13
+ #-----------------------------------------------
14
+ with st.spinner('loading ...'):
15
+ if pdf1:
16
+ doc_obj = PyPDF2.PdfReader(pdf1)
17
+ summary=' '
18
+ with st.spinner('Analyzing...'):
19
+ for i in range(0,len(doc_obj.pages)):
20
+ # creating a page object
21
+ pageObj = doc_obj.pages[i].extract_text() # extract one page's text
22
+ pageObj = pageObj.replace('\t\r','') # tab, enter
23
+ pageObj = pageObj.replace('\xa0','') # non-breaking spaces
24
+ # extracting text from page
25
+ page_text.append(pageObj) # the whole pdf --> txt
26
+ # st.session_state['page_text'] = page_text
27
+ st.success("Load successfully. Continue to next tab: Display")
28
+ else:
29
+ st.info("waiting for uploading ...")
30
+
31
+
32
+ with tab2:
33
+ if page_text is not None:
34
+ # st.write(type(page_text))
35
+ st.code(f'raw data: {page_text}')
36
+ else:
37
+ st.warning("Please upload a PDF to display the data.")
38
+
pages/2_📑Scanned Receipt.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st, base64, json, re
2
+ import mysql.connector
3
+ from datetime import datetime
4
+ from utils import ai, st_def, db
5
+ import pandas as pd
6
+
7
+
8
+ st_def.st_logo(title='👋 Scanned Recepit Extract')
9
+ tab1, tab2, tab3,tab4 = st.tabs(["Upload", "Display", "Save", "Database"])
10
+ uploaded_file = None
11
+ base64_image = None
12
+ model = 'gpt-4-turbo'
13
+
14
+ with tab1:
15
+ st.image("./data/scanned_sample.png")
16
+ st.header("Upload Receipt")
17
+ uploaded_file = st.file_uploader("Upload scanned receipt: ", type=["jpg", "jpeg", "png", "pdf"])
18
+ if uploaded_file is not None:
19
+ st.image(uploaded_file, caption='Uploaded Receipt')
20
+ base64_image = base64.b64encode(uploaded_file.read()).decode('utf-8')
21
+ st.text(base64_image)
22
+ st.success("Load successfully. Continue to next tab: Display")
23
+
24
+ with tab2:
25
+ if not base64_image:
26
+ st.error('Please upload scanned receipt first.')
27
+ else:
28
+ openai_api_key= st_def.st_sidebar()
29
+ if not openai_api_key:
30
+ st.info('Please enter OpenAI’s API key to continue extract the receipt uploaded.')
31
+ else:
32
+ var_for = """Given the receipt image provided, extract all relevant information and structure the output as detailed JSON that matches the database schema for storing receipt headers and line items. The receipt headers should include store name, slogan, address, store manager, phone number, transaction ID, date, time, cashier, subtotal, sales tax, total, gift card, charged amount, card type, authorization code, chip read, AID, issuer, policy ID, expiration date, survey message, survey website, user ID, password, and eligibility note. The line items should include SKU, description, details, and price for each item on the receipt. Exclude any sensitive information from the output. Format the JSON as follows:
33
+ {"receipt_headers": {"store_name": "", "slogan": "", "address": "", "store_manager": "",
34
+ "phone_number": "", "transaction_id": "", "date": "", "time": "",
35
+ "cashier": "", "subtotal": 0, "sales_tax": 0, "total": 0,
36
+ "gift_card": 0, "charged_amount": 0, "card_type": "", "auth_code": "",
37
+ "chip_read": "", "aid": "", "issuer": "", "policy_id": "",
38
+ "expiration_date": "", "survey_message": "", "survey_website": "", "user_id": "",
39
+ "password": "", "eligibility_note": "" },
40
+ "line_items": [{"sku": "", "description": "", "details": "", "price": 0}]}"""
41
+ # receipt_data_str = ai.ai_vision(var_for = var_for, openai_api_key=openai_api_key, model_v=model, base64_image=base64_image)
42
+ # with open('re.txt', 'w') as file:
43
+ # file.write(receipt_data_str)
44
+ # st.write(receipt_data_str)
45
+
46
+ with open('re1.txt', 'r') as file: receipt_data_str = file.read()
47
+
48
+ start_index = receipt_data_str.find("{") # Find the starting index of the JSON data (excluding the leading ```)
49
+ end_index = receipt_data_str.rfind("}")+1 # Find the ending index of the JSON data (excluding the trailing ```)
50
+ json_data = receipt_data_str[start_index:end_index] # Extract the JSON data as a substring
51
+
52
+ receipt_dict = json.loads(json_data)
53
+
54
+ col1, col2 = st.columns(2)
55
+
56
+ with col1:
57
+ st.header("Scanned Receipt")
58
+ st.image(uploaded_file, caption='Uploaded Receipt')
59
+
60
+ with col2:
61
+ st.header("Extracted Data")
62
+ st.write(receipt_dict)
63
+
64
+ db.mysql_insert_receipt(receipt_dict)
65
+
66
+ # Display success message
67
+ st.success("Message received successfully from the LLM.")
68
+
69
+ with tab3:
70
+ cursor, conn = db.mysql_conn()
71
+ st.header("Display the Data")
72
+ # Fetch all records from the receipt_headers table, excluding the time column
73
+ cursor.execute("SELECT store_name, slogan, address, store_manager, phone_number, transaction_id, date, cashier, subtotal, sales_tax, total, gift_card, charged_amount, card_type, auth_code, chip_read, aid, issuer, policy_id, expiration_date, survey_message, survey_website, user_id, password, eligibility_note FROM receipt_headers;")
74
+ headers = cursor.fetchall()
75
+
76
+ # Display the headers in a table
77
+ st.subheader("Receipt Headers")
78
+ st.table(headers)
79
+
80
+ # Fetch and display all records from the line_items table
81
+ st.subheader("Line Items")
82
+ cursor.execute("SELECT * FROM line_items;")
83
+ items = cursor.fetchall()
84
+ st.table(items)
85
+
86
+ # Close the cursor and the connection
87
+ cursor.close()
88
+ conn.close()
89
+
90
+ with tab4:
91
+ # Receipt headers data
92
+ receipt_headers_data = {
93
+ "store_name": "Starbucks E Food Court #16599",
94
+ "slogan": "OPERATED BY HMS",
95
+ "address": "Harry Reid Airport",
96
+ "store_manager": "",
97
+ "phone_number": "",
98
+ "transaction_id": "CHK 111704",
99
+ "date": "12/2/2022",
100
+ "time": "1:23 PM",
101
+ "cashier": "",
102
+ "subtotal": 6.00,
103
+ "sales_tax": 0.50,
104
+ "total": 6.50,
105
+ "gift_card": 0,
106
+ "charged_amount": 6.50,
107
+ "card_type": "MasterCard",
108
+ "auth_code": "",
109
+ "chip_read": "",
110
+ "aid": "",
111
+ "issuer": "",
112
+ "policy_id": "",
113
+ "expiration_date": "",
114
+ "survey_message": "We value your feedback! Scan the QR code below to share your experience.",
115
+ "survey_website": "https://hmshost.com/contact/",
116
+ "user_id": "",
117
+ "password": "",
118
+ "eligibility_note": ""
119
+ }
120
+
121
+ # Line items data
122
+ line_items_data = [
123
+ {
124
+ "sku": "",
125
+ "description": "1 GR GRN TEA LAT",
126
+ "details": "To Go",
127
+ "price": 6.00
128
+ },
129
+ {
130
+ "sku": "d34358axe",
131
+ "description": "2 GR APL",
132
+ "details": "To Go",
133
+ "price": 16.00
134
+ },
135
+ {
136
+ "sku": "12x3ce",
137
+ "description": "COF BAN SILK",
138
+ "details": "",
139
+ "price": 61.00
140
+ }
141
+ ]
142
+
143
+ # Create DataFrames
144
+ receipt_headers_df = pd.DataFrame(receipt_headers_data, index=[0])
145
+ line_items_df = pd.DataFrame(line_items_data)
146
+
147
+ # Display the DataFrames
148
+ st.write("Receipt Headers DataFrame:")
149
+ st.write(receipt_headers_df)
150
+
151
+ st.write("\nLine Items DataFrame:")
152
+ st.write(line_items_df)
re.txt ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "receipt_headers": {
3
+ "store_name": "Starbucks E Food Court #16599",
4
+ "slogan": "OPERATED BY HMS",
5
+ "address": "Harry Reid Airport",
6
+ "store_manager": "",
7
+ "phone_number": "",
8
+ "transaction_id": "CHK 111704",
9
+ "date": "12/2/2022",
10
+ "time": "1:23 PM",
11
+ "cashier": "",
12
+ "subtotal": 6.00,
13
+ "sales_tax": 0.50,
14
+ "total": 6.50,
15
+ "gift_card": 0,
16
+ "charged_amount": 6.50,
17
+ "card_type": "MasterCard",
18
+ "auth_code": "",
19
+ "chip_read": "",
20
+ "aid": "",
21
+ "issuer": "",
22
+ "policy_id": "",
23
+ "expiration_date": "",
24
+ "survey_message": "We value your feedback! Scan the QR code below to share your experience.",
25
+ "survey_website": "https://hmshost.com/contact/",
26
+ "user_id": "",
27
+ "password": "",
28
+ "eligibility_note": ""
29
+ },
30
+ "line_items": [
31
+ {
32
+ "sku": "",
33
+ "description": "1 GR GRN TEA LAT",
34
+ "details": "To Go",
35
+ "price": 6.00
36
+ }
37
+ {
38
+ "sku": "d34358axe",
39
+ "description": "2 GR APL",
40
+ "details": "To Go",
41
+ "price": 16.00
42
+ }
43
+ {
44
+ "sku": "12x3ce",
45
+ "description": "COF BAN SILK",
46
+ "details": "",
47
+ "price": 61.00
48
+ }
49
+ ]
50
+ }
re1.txt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here is the extracted information from the receipt image provided, structured as a JSON object according to the given schema.
2
+
3
+ ```json
4
+ {
5
+ "receipt_headers": {
6
+ "store_name": "Starbucks E Food Court #16599",
7
+ "slogan": "OPERATED BY HMS",
8
+ "address": "Harry Reid Airport",
9
+ "store_manager": "",
10
+ "phone_number": "",
11
+ "transaction_id": "CHK 111704",
12
+ "date": "12/2/2022",
13
+ "time": "1:23 PM",
14
+ "cashier": "",
15
+ "subtotal": 6.00,
16
+ "sales_tax": 0.50,
17
+ "total": 6.50,
18
+ "gift_card": 0,
19
+ "charged_amount": 6.50,
20
+ "card_type": "MasterCard",
21
+ "auth_code": "",
22
+ "chip_read": "",
23
+ "aid": "",
24
+ "issuer": "",
25
+ "policy_id": "",
26
+ "expiration_date": "",
27
+ "survey_message": "We value your feedback! Scan the QR code below to share your experience.",
28
+ "survey_website": "https://hmshost.com/contact/",
29
+ "user_id": "",
30
+ "password": "",
31
+ "eligibility_note": ""
32
+ },
33
+ "line_items": [
34
+ {
35
+ "sku": "",
36
+ "description": "1 GR GRN TEA LAT",
37
+ "details": "To Go",
38
+ "price": 6.00
39
+ }
40
+ ]
41
+ }
42
+ ```
43
+
44
+ Note: Some fields are left empty ("") as they are not provided in the receipt. Additional fields might be required to structure JSON perfectly according to a specified schema which were not visible or mentioned in the image of the receipt provided.
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ streamlit_extras
3
+ openai
4
+ tenacity
5
+ PyPDF2
6
+ mysql-connector-python
7
+ SQLAlchemy
8
+ mysqlclient
serialized_response.json ADDED
@@ -0,0 +1 @@
 
 
1
+ "The information extracted from the receipt image is structured into a JSON format as specified:\n\n```json\n{\n \"receipt_headers\": {\n \"store_name\": \"Trader Joe's\",\n \"slogan\": \"\",\n \"address\": \"100 Front Street Santa Cruz, CA 95060\",\n \"store_manager\": \"\",\n \"phone_number\": \"831-425-0140\",\n \"transaction_id\": \"****6000\",\n \"date\": \"\",\n \"time\": \"\",\n \"cashier\": \"\",\n \"subtotal\": 9.98,\n \"sales_tax\": 0,\n \"total\": 9.98,\n \"gift_card\": 0,\n \"charged_amount\": 9.98,\n \"card_type\": \"MasterCard\",\n \"auth_code\": \"N64K4H\",\n \"chip_read\": \"\",\n \"aid\": \"\",\n \"issuer\": \"\",\n \"policy_id\": \"\",\n \"expiration_date\": \"\",\n \"survey_message\": \"\",\n \"survey_website\": \"\",\n \"user_id\": \"\",\n \"password\": \"\",\n \"eligibility_note\": \"\"\n },\n \"line_items\": [\n {\n \"sku\": \"\",\n \"description\": \"WRAP ORG SOUTHWEST CHICK\",\n \"details\": \"\",\n \"price\": 5.39\n },\n {\n \"sku\": \"\",\n \"description\": \"CUT FRUITFUL MEDLEY 16 O\",\n \"details\": \"\",\n \"price\": 3.99\n }\n ]\n}\n```\n\nNote:\n- Fields such as the \"slogan\", \"store_manager\", \"date\", \"time\", \"cashier\", \"sales tax\", \"chip_read\", \"aid\", \"issuer\", \"policy_id\", \"expiration_date\", \"survey_message\", \"survey_website\", \"user_id\", \"password\", and \"eligibility_note\" were not available or not applicable from the data provided in the receipt and are thus left empty or set to default values.\n- The SKU for each item is not listed on the receipt, so these entries remain empty.\n- The payment details include truncation of the transaction ID for security, and similar truncation is applied for some parts of the payment card number.\n- The address is inferred to include city and state based on the typical formatting found on receipts, despite them not being distinctly separated in the text."
utils/__pycache__/ai.cpython-311.pyc ADDED
Binary file (2.55 kB). View file
 
utils/__pycache__/db.cpython-311.pyc ADDED
Binary file (8.23 kB). View file
 
utils/__pycache__/doc_processing.cpython-312.pyc ADDED
Binary file (10.8 kB). View file
 
utils/__pycache__/impage_process.cpython-311.pyc ADDED
Binary file (500 Bytes). View file
 
utils/__pycache__/st_def.cpython-311.pyc ADDED
Binary file (3.56 kB). View file
 
utils/__pycache__/st_def.cpython-312.pyc ADDED
Binary file (3.73 kB). View file
 
utils/__pycache__/ut_openai.cpython-311.pyc ADDED
Binary file (2.55 kB). View file
 
utils/__pycache__/ut_openai.cpython-312.pyc ADDED
Binary file (1.69 kB). View file
 
utils/__pycache__/utilities.cpython-312.pyc ADDED
Binary file (2.03 kB). View file
 
utils/ai.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ from tenacity import retry, wait_random_exponential, stop_after_attempt
3
+ # client = openai.OpenAI() # not acceptable in streamlit
4
+ # curl https://api.openai.com/v1/models -H "Authorization: Bearer sk-proj-FcKBzwDnp"
5
+
6
+ @retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
7
+ def aichat(messages, openai_api_key):
8
+ try:
9
+ client = openai.OpenAI(api_key = openai_api_key)
10
+ response = client.chat.completions.create(
11
+ messages=messages,
12
+ model="gpt-3.5-turbo-0125",
13
+ # stream=True,
14
+ # max_tokens=2000
15
+ )
16
+ return response.choices[0].message.content
17
+ except Exception as e:
18
+ print("Unable to generate ChatCompletion response")
19
+ print(f"Exception: {e}")
20
+ return e
21
+
22
+
23
+ @retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
24
+ def ai_vision(var_for, openai_api_key, model_v, base64_image):
25
+ try:
26
+ client = openai.OpenAI(api_key = openai_api_key)
27
+ response = client.chat.completions.create(
28
+ model=model_v,
29
+ messages=[
30
+ {
31
+ "role": "user",
32
+ "content": [
33
+ {"type": "text", "text": var_for},
34
+ {
35
+ "type": "image_url",
36
+ "image_url": {
37
+ "url": f"data:image/jpeg;base64,{base64_image}",
38
+ },
39
+ },
40
+ ],
41
+ }
42
+ ],
43
+ max_tokens=1024,
44
+ )
45
+
46
+ return response.choices[0].message.content
47
+ # return response.choices[0]
48
+ except Exception as e:
49
+ print("Unable to generate ChatCompletion response")
50
+ print(f"Exception: {e}")
51
+ return e
52
+
53
+
54
+ def get_embedding(text, model="text-embedding-3-small"):
55
+ # client = openai.OpenAI(api_key = openai_api_key)
56
+ text = text.replace("\n", " ")
57
+ # return client.embeddings.create(input = [text], model=model).data[0].embedding
58
+
59
+ # text = "test embedding"
60
+ # embeddings = get_embedding(text)
utils/db.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, mysql.connector, streamlit as st
2
+ from datetime import datetime
3
+
4
+ def mysql_conn():
5
+ conn = mysql.connector.connect(
6
+ host="mysql-omni-omni.b.aivencloud.com",
7
+ port='21906',
8
+ user="avnadmin",
9
+ password= os.environ.get('MYSQL_PWD'),
10
+ database = 'defaultdb', )
11
+ cursor = conn.cursor()
12
+ return cursor, conn
13
+
14
+ def mysql_check():
15
+ cursor, conn = mysql_conn()
16
+ cursor.execute("SHOW TABLES;")
17
+ # cursor.execute("DESCRIBE receipt_headers_allvarchar;")
18
+ cursor.close()
19
+ conn.close()
20
+
21
+
22
+ def mysql_create_receipt_table():
23
+ cursor, conn = mysql_conn()
24
+ cursor.execute("""
25
+ CREATE TABLE IF NOT EXISTS receipt_headers (
26
+ receipt_id INT AUTO_INCREMENT PRIMARY KEY,
27
+ store_name VARCHAR(255), slogan VARCHAR(255), address VARCHAR(255), store_manager VARCHAR(255), phone_number VARCHAR(50),
28
+ transaction_id VARCHAR(255), date DATE, time TIME, cashier VARCHAR(255), subtotal DECIMAL(10,2),
29
+ sales_tax DECIMAL(10,2), total DECIMAL(10,2), gift_card DECIMAL(10,2), charged_amount DECIMAL(10,2), card_type VARCHAR(50),
30
+ auth_code VARCHAR(50), chip_read VARCHAR(50), aid VARCHAR(50), issuer VARCHAR(255), policy_id VARCHAR(50),
31
+ expiration_date DATE, survey_message TEXT, survey_website VARCHAR(255), user_id VARCHAR(255), password VARCHAR(255), eligibility_note TEXT )
32
+ """)
33
+ # Create line_items table
34
+ cursor.execute("""
35
+ CREATE TABLE IF NOT EXISTS line_items (
36
+ line_item_id INT AUTO_INCREMENT PRIMARY KEY,
37
+ receipt_id INT, sku VARCHAR(255), description VARCHAR(255), details TEXT, price DECIMAL(10,2),
38
+ FOREIGN KEY (receipt_id) REFERENCES receipt_headers(receipt_id) )
39
+ """)
40
+ conn.commit()
41
+ cursor.close()
42
+ conn.close()
43
+
44
+
45
+ def mysql_create_receipt_table_allvarchar():
46
+ cursor, conn = mysql_conn()
47
+ cursor.execute("""
48
+ CREATE TABLE IF NOT EXISTS receipt_headers_allvarchar (
49
+ receipt_id INT AUTO_INCREMENT PRIMARY KEY,
50
+ store_name VARCHAR(255), slogan VARCHAR(255), address VARCHAR(255), store_manager VARCHAR(255), phone_number VARCHAR(50),
51
+ transaction_id VARCHAR(255), date VARCHAR(50), time VARCHAR(50), cashier VARCHAR(255), subtotal DECIMAL(10,2),
52
+ sales_tax DECIMAL(10,2), total DECIMAL(10,2), gift_card DECIMAL(10,2), charged_amount DECIMAL(10,2), card_type VARCHAR(50),
53
+ auth_code VARCHAR(50), chip_read VARCHAR(50), aid VARCHAR(50), issuer VARCHAR(255), policy_id VARCHAR(50),
54
+ expiration_date VARCHAR(50), survey_message TEXT, survey_website VARCHAR(255), user_id VARCHAR(255), password VARCHAR(255), eligibility_note TEXT )
55
+ """)
56
+ # Create line_items table
57
+ cursor.execute("""
58
+ CREATE TABLE IF NOT EXISTS line_items_allvarchar (
59
+ line_item_id INT AUTO_INCREMENT PRIMARY KEY,
60
+ receipt_id INT, sku VARCHAR(255), description VARCHAR(255), details TEXT, price DECIMAL(10,2),
61
+ FOREIGN KEY (receipt_id) REFERENCES receipt_headers(receipt_id))
62
+ """)
63
+ conn.commit()
64
+ cursor.close()
65
+ conn.close()
66
+
67
+ def mysql_insert_receipt(receipt_data):
68
+ cursor, conn = mysql_conn()
69
+ # Insert into receipt_headers
70
+ header_insert_query = """
71
+ INSERT INTO receipt_headers (store_name, slogan, address, store_manager, phone_number, transaction_id, date, time, cashier, subtotal, sales_tax, total, gift_card, charged_amount, card_type, auth_code, chip_read, aid, issuer, policy_id, expiration_date, survey_message, survey_website, user_id, password, eligibility_note)
72
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
73
+ """
74
+ header_info = receipt_data['receipt_headers']
75
+ line_items = receipt_data['line_items']
76
+ # Format date, time, and expiration_date
77
+ formatted_date = datetime.strptime(header_info['date'], '%m/%d/%Y').strftime('%Y-%m-%d')
78
+ formatted_time = datetime.strptime(header_info['time'], '%I:%M %p').strftime('%H:%M:%S')
79
+ # formatted_expiration_date = datetime.strptime(header_info['expiration_date'], '%m/%d/%Y').strftime('%Y-%m-%d')
80
+ formatted_expiration_date = datetime.strptime(header_info['expiration_date'], '%m/%d/%Y').strftime('%Y-%m-%d') if header_info['expiration_date'] else '01/01/2023'
81
+ formatted_expiration_date = datetime.strptime(header_info['expiration_date'], '%m/%d/%Y') if header_info['expiration_date'] else datetime.strptime('01/01/1000', '%m/%d/%Y')
82
+
83
+ # Prepare header values
84
+ header_values = (
85
+ header_info['store_name'],
86
+ header_info['slogan'],
87
+ header_info['address'],
88
+ header_info['store_manager'],
89
+ header_info['phone_number'],
90
+ header_info['transaction_id'],
91
+ formatted_date,
92
+ formatted_time,
93
+ header_info['cashier'],
94
+ header_info['subtotal'],
95
+ header_info['sales_tax'],
96
+ header_info['total'],
97
+ header_info['gift_card'],
98
+ header_info['charged_amount'],
99
+ header_info['card_type'],
100
+ header_info['auth_code'],
101
+ header_info['chip_read'],
102
+ header_info['aid'],
103
+ header_info['issuer'],
104
+ header_info['policy_id'],
105
+ formatted_expiration_date,
106
+ header_info['survey_message'],
107
+ header_info['survey_website'],
108
+ header_info['user_id'],
109
+ header_info['password'],
110
+ header_info['eligibility_note']
111
+ )
112
+
113
+ # Insert header values
114
+ cursor.execute(header_insert_query, header_values)
115
+ receipt_id = cursor.lastrowid
116
+
117
+ # Prepare and insert line items
118
+ line_item_insert_query = """
119
+ INSERT INTO line_items (receipt_id, sku, description, details, price)
120
+ VALUES (%s, %s, %s, %s, %s)
121
+ """
122
+
123
+ for item in line_items:
124
+ price = float(item['price'])
125
+ line_item_values = (
126
+ receipt_id,
127
+ item['sku'],
128
+ item['description'],
129
+ item.get('details', ''),
130
+ price
131
+ )
132
+
133
+ cursor.execute(line_item_insert_query, line_item_values)
134
+
135
+ # Commit and close the connection
136
+ conn.commit()
137
+ cursor.close()
138
+ conn.close()
139
+
140
+
utils/st_def.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_extras.add_vertical_space import add_vertical_space
3
+
4
+ def st_sidebar():
5
+ with st.sidebar:
6
+ # store_link = st.text_input("Enter Your Store URL:", value="http://hypech.com/StoreSpark", disabled=True, key="store_link")
7
+ openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
8
+ st.write("[Get an OpenAI API key](https://platform.openai.com/account/api-keys)")
9
+ add_vertical_space(2)
10
+ st.write('Made with ❤️ by [aiXpertLab](https://hypech.com)')
11
+ return openai_api_key
12
+
13
+ def st_logo(title="aiXpert!"):
14
+ st.title(title)
15
+
16
+ st.markdown("""
17
+ <style>
18
+ [data-testid="stSidebarNav"] {
19
+ background-image: url(https://hypech.com/images/logo/st_receiptbot.png);
20
+ background-size: 300px; /* Set the width and height of the image */
21
+ background-repeat: no-repeat;
22
+ padding-top: 80px;
23
+ background-position: 15px 10px;
24
+ }
25
+ </style>
26
+ """,
27
+ unsafe_allow_html=True,
28
+ )
29
+
30
+
31
+ def st_text_preprocessing_contents():
32
+ st.markdown("""
33
+ - Normalize Text
34
+ - Remove Unicode Characters
35
+ - Remove Stopwords
36
+ - Perform Stemming and Lemmatization
37
+ """)
38
+
39
+
40
+ def st_read_pdf():
41
+ st.markdown("""
42
+ Because OpenAI has a limit on the input prompt size, we would like to send the data to be summarized in parts.
43
+ There can be multiple ways to split the text. For the sake of simplicity, we will divide the whole book on the basis of pages.
44
+ A **better strategy** will be to split it on the basis of paragraphs. However, it will increase the number of API calls increasing the overall time.
45
+
46
+ We will store each page in a list and then summarize it.
47
+ """)
48
+ st.image("./images/book.png")
49
+
50
+ def st_summary():
51
+ st.markdown("Now we will start prompting. This is a matter of experiment to figure out the best prompt. However, there are a few basic guidelines on how to do it efficiently. In some upcoming articles, we will discuss the art of prompting in more detail. You can use the prompt for now, which has worked well for me. ")
52
+ # st.image("./images/featureengineering.png")
53
+
54
+ def st_case_study():
55
+ st.image("./images/NLP-Pipeline.png")
56
+ # main_contents="""
57
+ # ### 🚀 Bridge the Gap: Chatbots for Every Store 🍨
58
+ # Tired of missing out on sales due to limited customer support options? Struggling to keep up with growing customer inquiries? Store Spark empowers you to seamlessly integrate a powerful ChatGPT-powered chatbot into your website, revolutionizing your customer service and boosting engagement. No coding required! No modifications for current site needed!
59
+ # ### 📄Key Features📚:
60
+ # - 🔍 No Coding Required: Say goodbye to developer fees and lengthy website updates. Store Spark’s user-friendly API ensures a smooth integration process.
61
+ # - 📰 Empower Your Business: Offer instant customer support, improve lead generation, and boost conversion rates — all with minimal setup effort.
62
+ # - 🍨 Seamless Integration: Maintain your existing website design and user experience. Store Spark seamlessly blends in, providing a unified customer journey.
63
+ # """
64
+