here is a python program I created, but the issue is that most receipts just have the product, the price, and the date of purchase, but not the expiry dates. As such I want you to modify my program so that it can searches the internet for each product and finds the rough expiry period for it and calcualtes and approximate expiry date based on the purchase date on the receipt:
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
import pytesseract
import sqlite3
import re
from datetime import datetime, timedelta
import threading
import time
from plyer import notification
conn = sqlite3.connect('items.db')
c = conn.cursor()
Create table for items if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS items
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
expiration_date DATE NOT NULL)''')
conn.commit()
self.label = tk.Label(master, text="Receipt Expiration Tracker", font=("Helvetica", 16))
self.label.pack(pady=10)
self.upload_button = tk.Button(master, text="Upload Receipt", command=self.upload_receipt)
self.upload_button.pack(pady=5)
self.view_items_button = tk.Button(master, text="View Items", command=self.view_items)
self.view_items_button.pack(pady=5)
self.check_expirations() # Start checking for expiring items
def upload_receipt(self):
file_path = filedialog.askopenfilename(
filetypes=[("Image Files", "*.png *.jpg *.jpeg *.bmp *.tiff")])
if file_path:
try:
# Open image
image = Image.open(file_path)
# Perform OCR using pytesseract
text = pytesseract.image_to_string(image)
# Extract items and expiration dates
items = self.extract_items(text)
if items:
self.save_items(items)
messagebox.showinfo("Success", "Items have been added successfully!")
else:
messagebox.showwarning("No Items Found", "No items with expiration dates were found in the receipt.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred while processing the receipt: {e}")
def extract_items(self, text):
lines = text.split('\n')
items = []
# Regular expression to match dates in formats like MM/DD/YYYY, MM-DD-YYYY, MM/DD/YY, etc.
date_pattern = re.compile(
r'(\b(0?[1-9]|1[0-2])[\/\-\.](0?[1-9]|[12][0-9]|3[01])[\/\-\.](\d{2}|\d{4})\b)')
for line in lines:
line = line.strip()
if not line:
continue
date_match = date_pattern.search(line)
if date_match:
date_str = date_match.group(0)
name = line[:line.find(date_str)].strip()
if name:
expiration_date = self.parse_date(date_str)
if expiration_date:
items.append({
'name': name,
'expiration_date': expiration_date
})
return items
def parse_date(self, date_str):
for fmt in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y',
'%m/%d/%y', '%m-%d-%y', '%m.%d.%y'):
try:
return datetime.strptime(date_str, fmt).date()
except ValueError:
continue
return None
def save_items(self, items):
for item in items:
c.execute("INSERT INTO items (name, expiration_date) VALUES (?, ?)",
(item['name'], item['expiration_date']))
conn.commit()
def view_items(self):
items_window = tk.Toplevel(self.master)
items_window.title("Tracked Items")
c.execute("SELECT name, expiration_date FROM items ORDER BY expiration_date")
items = c.fetchall()
if items:
for idx, item in enumerate(items):
name, expiration_date = item
label = tk.Label(items_window, text=f"{name} - Expires on: {expiration_date}")
label.pack(anchor='w')
else:
label = tk.Label(items_window, text="No items are currently being tracked.")
label.pack()
def check_expirations(self):
# Check for items that are expiring in the next day
threading.Thread(target=self.expiration_checker, daemon=True).start()
def expiration_checker(self):
while True:
today = datetime.now().date()
upcoming = today + timedelta(days=1)
c.execute("SELECT name, expiration_date FROM items WHERE expiration_date = ?", (upcoming,))
expiring_items = c.fetchall()
for item in expiring_items:
name, expiration_date = item
self.send_notification(name, expiration_date)
# Sleep for 24 hours before checking again
time.sleep(86400) # 86400 seconds in a day
def send_notification(self, name, expiration_date):
notification.notify(
title='Item Expiring Soon',
message=f'Your item "{name}" will expire on {expiration_date}.',
timeout=10 # Notification stays for 10 seconds
)
# Close the database connection when the app is closed
conn.close()
if name == "main":
main()
Here is the modified program that extracts product names from the receipt, finds the average expiry period for each product from a predefined list, and calculates the approximate expiration date based on the purchase date on the receipt:
python
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
import pytesseract
import sqlite3
import re
from datetime import datetime, timedelta
import threading
import time
from plyer import notification
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Create or connect to SQLite database
conn = sqlite3.connect('items.db')
c = conn.cursor()
# Create table for items if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS items
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
expiration_date DATE NOT NULL)''')
conn.commit()
class ReceiptTrackerApp:
def __init__(self, master):
self.master = master
master.title("Receipt Expiration Tracker")
self.label = tk.Label(master, text="Receipt Expiration Tracker", font=("Helvetica", 16))
self.label.pack(pady=10)
self.upload_button = tk.Button(master, text="Upload Receipt", command=self.upload_receipt)
self.upload_button.pack(pady=5)
self.view_items_button = tk.Button(master, text="View Items", command=self.view_items)
self.view_items_button.pack(pady=5)
# Define the expiry periods for common products (in days)
self.EXPIRY_PERIODS = {
'milk': 7,
'egg': 21,
'bread': 3,
'cheese': 14,
'yogurt': 14,
'butter': 60,
'apple': 30,
'banana': 7,
'chicken': 2,
'beef': 3,
'fish': 2,
'lettuce': 5,
'broccoli': 7,
'rice': 180,
'pasta': 365,
# Add more products and their average expiry periods here
}
self.DEFAULT_EXPIRY_DAYS = 7 # Default expiry period if product is not found
self.check_expirations() # Start checking for expiring items
def upload_receipt(self):
file_path = filedialog.askopenfilename(
filetypes=[("Image Files", "*.png *.jpg *.jpeg *.bmp *.tiff")])
if file_path:
try:
# Open image
image = Image.open(file_path)
# Perform OCR using pytesseract
text = pytesseract.image_to_string(image)
# Extract items and their estimated expiration dates
items = self.extract_items(text)
if items:
self.save_items(items)
messagebox.showinfo("Success", "Items have been added successfully!")
else:
messagebox.showwarning("No Items Found", "No items were found in the receipt.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred while processing the receipt: {e}")
def extract_items(self, text):
lines = text.split('\n')
items = []
# Regular expression to match dates in formats like MM/DD/YYYY, MM-DD-YYYY, MM/DD/YY, etc.
date_pattern = re.compile(
r'(\b(0?[1-9]|1[0-2])[\/\-\.](0?[1-9]|[12][0-9]|3[01])[\/\-\.](\d{2}|\d{4})\b)')
# Attempt to find the purchase date from the receipt
purchase_date = None
for line in lines:
line = line.strip()
if not line:
continue
date_match = date_pattern.search(line)
if date_match:
date_str = date_match.group(0)
purchase_date = self.parse_date(date_str)
if purchase_date:
break # Assuming the first date found is the purchase date
# If no purchase date is found, use today's date
if not purchase_date:
purchase_date = datetime.now().date()
# Regular expression to match prices like $1.99, 1.99
price_pattern = re.compile(r'\$?\d+\.\d{2}')
for line in lines:
line = line.strip()
if not line:
continue
# Skip lines with date
if date_pattern.search(line):
continue
# Look for lines with prices
price_match = price_pattern.search(line)
if price_match:
# Assuming the product name is before the price
price_str = price_match.group(0)
name = line[:line.find(price_str)].strip()
if name:
items.append({
'name': name,
'purchase_date': purchase_date
})
return items
def parse_date(self, date_str):
for fmt in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y',
'%m/%d/%y', '%m-%d-%y', '%m.%d.%y'):
try:
return datetime.strptime(date_str, fmt).date()
except ValueError:
continue
return None
def get_expiry_period(self, product_name):
# Convert product name to lowercase for matching
name = product_name.lower()
expiry_days = None
# Try to find an exact match
if name in self.EXPIRY_PERIODS:
expiry_days = self.EXPIRY_PERIODS[name]
else:
# Try to find a product that contains the product name
for key in self.EXPIRY_PERIODS.keys():
if key in name:
expiry_days = self.EXPIRY_PERIODS[key]
break
# If not found, assign default expiry days
if expiry_days is None:
expiry_days = self.DEFAULT_EXPIRY_DAYS
return expiry_days
def save_items(self, items):
for item in items:
name = item['name']
purchase_date = item['purchase_date']
# Get the expiry period in days for the item
expiry_days = self.get_expiry_period(name)
if expiry_days:
expiration_date = purchase_date + timedelta(days=expiry_days)
# Save the item with the calculated expiration date
c.execute("INSERT INTO items (name, expiration_date) VALUES (?, ?)",
(name, expiration_date))
else:
# If expiry period is not found, skip the item or assign a default value
pass
conn.commit()
def view_items(self):
items_window = tk.Toplevel(self.master)
items_window.title("Tracked Items")
c.execute("SELECT name, expiration_date FROM items ORDER BY expiration_date")
items = c.fetchall()
if items:
for idx, item in enumerate(items):
name, expiration_date = item
label = tk.Label(items_window, text=f"{name} - Expires on: {expiration_date}")
label.pack(anchor='w')
else:
label = tk.Label(items_window, text="No items are currently being tracked.")
label.pack()
def check_expirations(self):
# Check for items that are expiring soon
threading.Thread(target=self.expiration_checker, daemon=True).start()
def expiration_checker(self):
while True:
today = datetime.now().date()
upcoming = today + timedelta(days=1)
c.execute("SELECT name, expiration_date FROM items WHERE expiration_date = ?", (upcoming,))
expiring_items = c.fetchall()
for item in expiring_items:
name, expiration_date = item
self.send_notification(name, expiration_date)
# Sleep for 24 hours before checking again
time.sleep(86400) # 86400 seconds in a day
def send_notification(self, name, expiration_date):
notification.notify(
title='Item Expiring Soon',
message=f'Your item "{name}" will expire on {expiration_date}.',
timeout=10 # Notification stays for 10 seconds
)
def main():
root = tk.Tk()
app = ReceiptTrackerApp(root)
root.mainloop()
# Close the database connection when the app is closed
conn.close()
if __name__ == "__main__":
main()
Explanation of Changes:
Extracting Purchase Date:
The extract_items method has been updated to search for the purchase date in the receipt text using the date_pattern regular expression.
If no date is found, it defaults to the current date.
Extracting Product Names:
The program assumes that product lines contain both a product name and a price.
It uses a regular expression price_pattern to find lines with prices and extracts the product name from those lines.
Defining Expiry Periods:
An EXPIRY_PERIODS dictionary has been added to the __init__ method, mapping common product names to their average expiry periods in days.
A DEFAULT_EXPIRY_DAYS is set for products not found in the dictionary.
Calculating Expiration Dates:
The get_expiry_period method retrieves the expiry period for each product.
The save_items method calculates the expiration date by adding the expiry period to the purchase date.
Notifications and Item Tracking:
The rest of the program remains similar, tracking items and notifying the user when items are about to expire.
Note:
You may need to expand the EXPIRY_PERIODS dictionary with more products relevant to your needs.
The receipt text extraction heavily depends on the quality of the OCR and the formatting of the receipt.
Adjust the regular expressions if your receipts have different formats.