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

Added new functionality to recommendation and filtering scripts. #802

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,4 @@ enforcement ladder](https://github.com/mozilla/diversity).

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
https://www.contributor-covenant.org/translations. correct it
68 changes: 35 additions & 33 deletions Coverpage.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@
justify-content: center;
align-items: center;
text-align: center;
position: relative; /* Ensure container can position children absolutely */
position: relative;
}

.explore-btn {
margin-left: 35%;
margin-top: 20px;
padding: 15px 30px;
font-size: 1.6rem;
Expand All @@ -41,7 +40,7 @@
cursor: pointer;
transition: all 0.3s ease-in-out;
animation: pulse 1.5s infinite;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}

.explore-btn:hover {
Expand All @@ -61,34 +60,33 @@
}
}

/* SVG Styles */
svg {
margin-left: 35%;
font-family: Algerian;
width: 100%;
height: auto; /* Maintain aspect ratio */
max-width: 600px; /* Limit size */
height: auto;
max-width: 600px;
}

svg text {
animation: stroke 5s infinite alternate;
stroke-width: 2;
stroke: #582f0e;
font-size: 100px;
}

@keyframes stroke {
0% {
fill: rgba(72,138,204,0);
fill: rgba(72, 138, 204, 0);
stroke: #582f0e;
stroke-dashoffset: 25%;
stroke-dasharray: 0 50%;
stroke-width: 2;
}
70% {
fill: rgba(72,138,204,0);
fill: rgba(72, 138, 204, 0);
stroke: rgb(253, 137, 137);
}
80% {
fill: rgba(72,138,204,0);
fill: rgba(72, 138, 204, 0);
stroke: #582f0e;
stroke-width: 3;
}
Expand All @@ -103,25 +101,23 @@

@media screen and (max-width: 1095.54px) {
svg text {
font-size: 100px; /* Adjust font size for smaller screens */

font-size: 50px; /* Adjust font size for smaller screens */
}
}

.small-text {
font-size: 1.5rem; /* Smaller font size for "Welcome to" */
color: rgb(136, 9, 9);
text-transform: uppercase;
text-decoration-thickness: 50px;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
display: block;
margin-top: 70px;
margin-left: 35%;
}
font-size: 1.5rem;
color: rgb(136, 9, 9);
text-transform: uppercase;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
display: block;
margin-top: 70px;
}
</style>
</head>
<body>
<div class="container">
<span class="small-text">Welcome to</span><br>
<span class="small-text">Welcome to</span>
<!-- Animated SVG Title -->
<svg viewBox="0 0 800 200">
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">
Expand All @@ -135,24 +131,30 @@
<script>
function explore() {
alert("Let's explore the Retro World!");
// Redirect to index.html
// Redirect to index.html
window.location.href = "index.html";
}
</script>
<script>

window.embeddedChatbotConfig = {
chatbotId: "dGlQ5bP-F7GodLWzgrVAx",
domain: "www.chatbase.co"
}
</script>
<script
chatbotId: "dGlQ5bP-F7GodLWzgrVAx",
domain: "www.chatbase.co"
};
</script>
<script
src="https://www.chatbase.co/embed.min.js"
chatbotId="dGlQ5bP-F7GodLWzgrVAx"
domain="www.chatbase.co"
defer>
</script>
</script>

<div class="gtranslate_wrapper"></div>
<script>window.gtranslateSettings = {"default_language":"en","detect_browser_language":true,"wrapper_selector":".gtranslate_wrapper"}</script>
<script>
window.gtranslateSettings = {
"default_language": "en",
"detect_browser_language": true,
"wrapper_selector": ".gtranslate_wrapper"
};
</script>
<script src="https://cdn.gtranslate.net/widgets/latest/float.js" defer></script>
</body>
</html>
81 changes: 36 additions & 45 deletions cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ function addItemToCart() {
addToCart(itemName, itemPrice);
}

const addToCart = function(name, price){
const addToCart = function(name, price) {
let cartItems = localStorage.getItem('cartItems');
cartItems = cartItems ? JSON.parse(cartItems) : [];
if(name==null && price==null) return;
if (name == null || price == null) return; // Changed && to || for better null handling

const existingItem = cartItems.find(item => item.name === name);
if (!existingItem) {
cartItems.push({ name, price });
Expand All @@ -17,7 +18,6 @@ const addToCart = function(name, price){

updateCartDisplay();
calculateBill();

}

const updateCartDisplay = function() {
Expand All @@ -39,63 +39,54 @@ const updateCartDisplay = function() {
});
}


// calculate total bill amount
let total = 0;
const calculateBill = ()=>{
itemPrices = document.querySelectorAll(".price");
for (p of itemPrices){
if (p!=null){
console.log(p.innerText);
total += parseFloat(p.innerText.replace('$',''));
let total = 0; // Moved total initialization here to reset it every time bill is calculated
const calculateBill = () => {
total = 0; // Reset total before calculation
const itemPrices = document.querySelectorAll(".price");
itemPrices.forEach(p => {
if (p != null) {
total += parseFloat(p.innerText.replace('$', ''));
}
}
});

console.log(total);
if(total!=0 && !isNaN(total)){
document.getElementById("bill").innerText = "$" + total.toFixed(2)
if (total !== 0 && !isNaN(total)) {
document.getElementById("bill").innerText = "$" + total.toFixed(2);
} else {
document.getElementById("bill").innerText = "$0.00"; // Reset bill display if total is zero
}

}

document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('DOMContentLoaded', function() {
addItemToCart();
});

let orderBtn = document.querySelector(".butt");
orderBtn.addEventListener("click", ()=>{
if(total==0){
alert("Please add something in the cart to place the order");
}
else{

alert("Order placed!");
}
})
orderBtn.addEventListener("click", () => {
if (total === 0) {
alert("Please add something to the cart to place the order");
} else {
alert("Order placed!");
}
});

// Prioritizing Image Loading
<script>
// Critical images
const criticalImages = document.querySelectorAll('.critical-image');

// Lazy load other images
const lazyImages = document.querySelectorAll('img[data-src]');
const criticalImages = document.querySelectorAll('.critical-image');
const lazyImages = document.querySelectorAll('img[data-src]');

// Load critical images immediately
criticalImages.forEach(image => {
// Load critical images immediately
criticalImages.forEach(image => {
image.src = image.dataset.src;
});
});

// Use Intersection Observer for lazy loading
const observer = new IntersectionObserver(entries => {
// Use Intersection Observer for lazy loading
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
});

lazyImages.forEach(image => observer.observe(image));
</script>
});

lazyImages.forEach(image => observer.observe(image));
15 changes: 13 additions & 2 deletions collaborative_filtering.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import pandas as pd
from surprise import Dataset, Reader, SVD
from surprise.model_selection import train_test_split, accuracy

# Load data from database
data = cursor.execute('SELECT user_id, item_id, interaction_type FROM user_interactions').fetchall()

# Convert to DataFrame and ensure interaction_type is treated as a rating
df = pd.DataFrame(data, columns=['user_id', 'item_id', 'interaction_type'])

# Check if interaction_type is within the expected rating scale
if df['interaction_type'].max() > 5 or df['interaction_type'].min() < 1:
raise ValueError("Interaction type values must be within the range 1 to 5.")

# Convert to Surprise dataset
reader = Reader(rating_scale=(1, 5))
dataset = Dataset.load_from_df(pd.DataFrame(data, columns=['user_id', 'item_id', 'interaction_type']), reader)
dataset = Dataset.load_from_df(df[['user_id', 'item_id', 'interaction_type']], reader)

# Train-test split
trainset, testset = train_test_split(dataset, test_size=0.25)
Expand All @@ -17,4 +25,7 @@

# Test model
predictions = algo.test(testset)
accuracy.rmse(predictions)

# Calculate and print RMSE
rmse = accuracy.rmse(predictions)
print(f'Root Mean Squared Error: {rmse}')
14 changes: 12 additions & 2 deletions content_based_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,22 @@

# Function to get recommendations
def get_recommendations(item_id, cosine_sim=cosine_sim):
idx = next(index for (index, d) in enumerate(items) if d["id"] == item_id)
# Find the index of the item that matches the given id
idx = next((index for (index, d) in enumerate(items) if d["id"] == item_id), None)
if idx is None:
return [] # Return empty if item_id is not found

# Get similarity scores for the selected item
sim_scores = list(enumerate(cosine_sim[idx]))
# Sort the items based on the similarity scores
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the scores of the top 3 similar items, excluding the first one (itself)
sim_scores = sim_scores[1:4]

# Get the item indices
item_indices = [i[0] for i in sim_scores]
return [items[i]['id'] for i in item_indices]

# Example usage
print(get_recommendations(101))
recommended_ids = get_recommendations(101)
print("Recommended item IDs:", recommended_ids)
22 changes: 14 additions & 8 deletions data_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,32 @@
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()

# Create table
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_interactions (
user_id INTEGER,
item_id INTEGER,
interaction_type TEXT,
timestamp DATETIME
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')

# Function to log interaction
def log_interaction(user_id, item_id, interaction_type):
timestamp = datetime.now()
cursor.execute('''
INSERT INTO user_interactions (user_id, item_id, interaction_type, timestamp)
VALUES (?, ?, ?, ?)
''', (user_id, item_id, interaction_type, timestamp))
conn.commit()
timestamp = datetime.now() # Get the current timestamp
try:
cursor.execute('''
INSERT INTO user_interactions (user_id, item_id, interaction_type, timestamp)
VALUES (?, ?, ?, ?)
''', (user_id, item_id, interaction_type, timestamp))
conn.commit() # Commit changes to the database
except sqlite3.Error as e:
print(f"An error occurred: {e}")

# Example usage
log_interaction(1, 101, 'click')
log_interaction(1, 102, 'view')
log_interaction(2, 101, 'purchase')

# Close the connection
conn.close()
Loading