Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SPD-105 - fix: Updated transaction table for Apriori algorithm, updat… #54

Merged
merged 2 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 28 additions & 18 deletions src/apriori/apriori_algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import datetime
from sqlalchemy import create_engine, text
import logging
import json

# Enable SQLAlchemy logging
logging.basicConfig()
Expand Down Expand Up @@ -44,23 +45,29 @@
one_week_ago = today - datetime.timedelta(days=7)

query = """
SELECT ip.transaction_id, d.name AS item_name
FROM items_purchased ip
JOIN drink_item d ON ip.item_id = d.id
JOIN transaction t ON ip.transaction_id = t.id
WHERE DATE(t.timestamp) BETWEEN :one_week_ago AND :today
UNION
SELECT ip.transaction_id, f.name AS item_name
FROM items_purchased ip
JOIN food_item f ON ip.item_id = f.id
JOIN transaction t ON ip.transaction_id = t.id
WHERE DATE(t.timestamp) BETWEEN :one_week_ago AND :today
SELECT id, items
FROM transaction
WHERE DATE(timestamp) BETWEEN :one_week_ago AND :today
"""
result = connection.execute(text(query), {"one_week_ago": one_week_ago, "today": today})
rows = result.fetchall()

# Convert data to a DataFrame
df = pd.DataFrame(rows, columns=['transaction_id', 'item_name'])
df = pd.DataFrame(rows, columns=['transaction_id', 'items'])

# Function to load JSON items with error handling
def load_json(items):
try:
return json.loads(items)
except json.JSONDecodeError:
return None

# Convert JSON items to lists and explode the lists into separate rows
df['items'] = df['items'].apply(load_json)
df = df.explode('items').dropna(subset=['items']).reset_index(drop=True)

# Rename 'items' column to 'item_name'
df = df.rename(columns={'items': 'item_name'})

# Print the raw data for inspection
print("Raw DataFrame:")
Expand Down Expand Up @@ -95,9 +102,10 @@
print("Association Rules DataFrame:")
print(rules.head())

# Insert only the rule with the highest conviction
if not rules.empty:
top_rule = rules.iloc[0] # Get the rule with the highest conviction
# Insert the top 5 rules into the database
if not rules.empty:
top_rules = rules.head(5) # Get the top 5 rules with the highest conviction
for index, top_rule in top_rules.iterrows():
antecedents = ', '.join(list(top_rule['antecedents']))
consequents = ', '.join(list(top_rule['consequents']))

Expand All @@ -118,11 +126,13 @@
"conviction": float(top_rule['conviction'])
}
)
print("Inserted top rule successfully.")
connection.commit() # Commit the transaction
print(f"Inserted rule {index + 1} successfully.")
except Exception as e:
print(f"Error inserting top rule: {str(e)}")
print(f"Error inserting rule {index + 1}: {str(e)}")
# Handle error (rollback, logging, etc.)

connection.commit() # Commit all transactions once all rules are inserted


# Close the connection
connection.close()
Binary file added src/images/logo_with_bg.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@
<tr>
<th>Top Pick</th>
<th></th>
<th>Popular Combo</th>
<th>Likely Paired With</th>
</tr>
</thead>
<tbody>
Expand Down Expand Up @@ -313,7 +313,7 @@
<td colspan='3' style='text-align: center;'>
<img class='pt-2 card-img-top' src='images/empty.png' style='max-width: 250px; max-height: 250px;'>
<br>
Oops! It looks like there's no data available.
Oops! It looks like there's no available data.
</td>
</tr>";
}
Expand Down
6 changes: 3 additions & 3 deletions src/javascript/reports.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
async function downloadPDF() {
const { jsPDF } = window.jspdf;
const logo = "images/logo-removebg-preview.png";
const logo = "images/logo_with_bg.png";

// Create a new PDF document
const doc = new jsPDF();
Expand Down Expand Up @@ -151,12 +151,12 @@ async function downloadPDF() {
},
});

// Top Pick and Popular Combo Table
// Top Pick and Likely Paired With Table
doc.setFontSize(14);
doc.setFont("Helvetica", "bold");
doc.text("Weekly Top Sold Products", 15, doc.previousAutoTable.finalY + 10);

const topPickHeaders = ["Top Pick", "", "Popular Combo"];
const topPickHeaders = ["Top Pick", "", "Likely Paired With"];
doc.autoTable({
startY: doc.previousAutoTable.finalY + 15,
head: [topPickHeaders],
Expand Down
Loading