recommendation engine 75% polished
This commit is contained in:
@@ -33,7 +33,7 @@ exports.getAllProducts = async (req, res) => {
|
||||
I.URL AS ProductImage,
|
||||
C.Name AS Category
|
||||
FROM Product P
|
||||
JOIN Image_URL I ON p.ProductID = i.ProductID
|
||||
JOIN Image_URL I ON P.ProductID = I.ProductID
|
||||
JOIN User U ON P.UserID = U.UserID
|
||||
JOIN Category C ON P.CategoryID = C.CategoryID;
|
||||
`);
|
||||
@@ -60,9 +60,10 @@ exports.getProductById = async (req, res) => {
|
||||
try {
|
||||
const [data] = await db.execute(
|
||||
`
|
||||
SELECT p.*, i.URL AS image_url
|
||||
SELECT p.*,U.Name AS SellerName, i.URL AS image_url
|
||||
FROM Product p
|
||||
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
|
||||
JOIN User U ON p.UserID = U.UserID
|
||||
WHERE p.ProductID = ?
|
||||
`,
|
||||
[id],
|
||||
|
||||
39
backend/controllers/recommendation.js
Normal file
39
backend/controllers/recommendation.js
Normal file
@@ -0,0 +1,39 @@
|
||||
const db = require("../utils/database");
|
||||
|
||||
// TODO: Get the recommondaed product given the userID
|
||||
exports.RecommondationByUserId = async (req, res) => {
|
||||
const { id } = req.body;
|
||||
try {
|
||||
const [data, fields] = await db.execute(
|
||||
`
|
||||
SELECT
|
||||
P.ProductID,
|
||||
P.Name AS ProductName,
|
||||
P.Price,
|
||||
P.Date AS DateUploaded,
|
||||
U.Name AS SellerName,
|
||||
I.URL AS ProductImage,
|
||||
C.Name AS Category
|
||||
FROM Product P
|
||||
JOIN Image_URL I ON P.ProductID = I.ProductID
|
||||
JOIN User U ON P.UserID = U.UserID
|
||||
JOIN Category C ON P.CategoryID = C.CategoryID
|
||||
JOIN Recommendation R ON P.ProductID = R.RecommendedProductID
|
||||
Where R.UserID = ?;`,
|
||||
[id],
|
||||
);
|
||||
|
||||
console.log(data);
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Products fetched successfully",
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error finding products:", error);
|
||||
return res.status(500).json({
|
||||
found: false,
|
||||
error: "Database error occurred",
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -6,6 +6,7 @@ const db = require("./utils/database");
|
||||
const userRouter = require("./routes/user");
|
||||
const productRouter = require("./routes/product");
|
||||
const searchRouter = require("./routes/search");
|
||||
const recommendedRouter = require("./routes/recommendation");
|
||||
const { generateEmailTransporter } = require("./utils/mail");
|
||||
const {
|
||||
cleanupExpiredCodes,
|
||||
@@ -36,6 +37,7 @@ checkDatabaseConnection(db);
|
||||
app.use("/api/user", userRouter); //prefix with /api/user
|
||||
app.use("/api/product", productRouter); //prefix with /api/product
|
||||
app.use("/api/search_products", searchRouter); //prefix with /api/product
|
||||
app.use("/api/Engine", recommendedRouter); //prefix with /api/
|
||||
|
||||
// Set up a scheduler to run cleanup every hour
|
||||
setInterval(cleanupExpiredCodes, 60 * 60 * 1000);
|
||||
|
||||
8
backend/routes/recommendation.js
Normal file
8
backend/routes/recommendation.js
Normal file
@@ -0,0 +1,8 @@
|
||||
// routes/product.js
|
||||
const express = require("express");
|
||||
const { RecommondationByUserId } = require("../controllers/recommendation");
|
||||
const router = express.Router();
|
||||
|
||||
router.post("/recommended", RecommondationByUserId);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,12 +1,60 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { Tag, Book, Laptop, Sofa, Utensils, Gift, Heart } from "lucide-react";
|
||||
import { Tag, Heart } from "lucide-react";
|
||||
|
||||
const Home = () => {
|
||||
const navigate = useNavigate();
|
||||
const [listings, setListings] = useState([]);
|
||||
const [recommended, setRecommended] = useState([]);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchrecomProducts = async () => {
|
||||
// Get the user's data from localStorage
|
||||
const storedUser = JSON.parse(sessionStorage.getItem("user"));
|
||||
console.log(storedUser);
|
||||
try {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/engine/recommended",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
id: storedUser.ID,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error("Failed to fetch products");
|
||||
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
if (data.success) {
|
||||
setRecommended(
|
||||
data.data.map((product) => ({
|
||||
id: product.ProductID,
|
||||
title: product.ProductName, // Use the alias from SQL
|
||||
price: product.Price,
|
||||
category: product.Category, // Ensure this gets the category name
|
||||
image: product.ProductImage, // Use the alias for image URL
|
||||
condition: "New", // Modify based on actual data
|
||||
seller: product.SellerName, // Fetch seller name properly
|
||||
datePosted: product.DateUploaded, // Use the actual date
|
||||
isFavorite: false, // Default state
|
||||
})),
|
||||
);
|
||||
} else {
|
||||
throw new Error(data.message || "Error fetching products");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
setError(error.message);
|
||||
}
|
||||
};
|
||||
fetchrecomProducts();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProducts = async () => {
|
||||
try {
|
||||
@@ -134,25 +182,25 @@ const Home = () => {
|
||||
id="RecomContainer"
|
||||
className="overflow-x-auto whitespace-nowrap flex space-x-6 scroll-smooth scrollbar-hide px-10 pl-0"
|
||||
>
|
||||
{listings.map((listing) => (
|
||||
{recommended.map((recommended) => (
|
||||
<Link
|
||||
key={listing.id}
|
||||
to={`/product/${listing.id}`}
|
||||
key={recommended.id}
|
||||
to={`/product/${recommended.id}`}
|
||||
className="bg-white border border-gray-200 hover:shadow-md transition-shadow w-70 flex-shrink-0 relative"
|
||||
>
|
||||
<div className="relative">
|
||||
<img
|
||||
src={listing.image}
|
||||
alt={listing.title}
|
||||
src={recommended.image}
|
||||
alt={recommended.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={(e) => toggleFavorite(listing.id, e)}
|
||||
onClick={(e) => toggleFavorite(recommended.id, e)}
|
||||
className="absolute top-2 right-2 p-2 bg-white rounded-full shadow-sm"
|
||||
>
|
||||
<Heart
|
||||
className={`h-6 w-6 ${
|
||||
listing.isFavorite
|
||||
recommended.isFavorite
|
||||
? "text-red-500 fill-red-500"
|
||||
: "text-gray-400"
|
||||
}`}
|
||||
@@ -162,25 +210,25 @@ const Home = () => {
|
||||
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-gray-800 leading-tight">
|
||||
{listing.title}
|
||||
{recommended.title}
|
||||
</h3>
|
||||
<span className="font-semibold text-green-600 block mt-1">
|
||||
${listing.price}
|
||||
${recommended.price}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center text-sm text-gray-500 mt-2">
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{listing.category}</span>
|
||||
<span>{recommended.category}</span>
|
||||
<span className="mx-2">•</span>
|
||||
<span>{listing.condition}</span>
|
||||
<span>{recommended.condition}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center pt-2 border-t border-gray-100 mt-3">
|
||||
<span className="text-xs text-gray-500">
|
||||
{listing.datePosted}
|
||||
{recommended.datePosted}
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{listing.seller}
|
||||
{recommended.seller}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -201,10 +201,7 @@ const ProductDetail = () => {
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{product.Category}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-gray-600">
|
||||
<span className="font-medium">Condition:</span>
|
||||
<span className="ml-1">{product.condition}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center text-gray-600">
|
||||
<Calendar className="h-4 w-4 mr-1" />
|
||||
<span>Posted on {product.Date}</span>
|
||||
@@ -287,11 +284,10 @@ const ProductDetail = () => {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-medium text-gray-800">
|
||||
{product.UserID || "Unknown Seller"}
|
||||
{product.SellerName || "Unknown Seller"}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
Member since{" "}
|
||||
{product.seller ? product.seller.memberSince : "N/A"}
|
||||
Member since {product.SellerName}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -415,64 +415,10 @@ const Settings = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Privacy Section */}
|
||||
<div className="bg-white border border-gray-200 mb-6">
|
||||
<div className="border-b border-gray-200 p-4">
|
||||
<div className="flex items-center">
|
||||
<Shield className="h-5 w-5 text-gray-500 mr-2" />
|
||||
<h2 className="text-lg font-medium text-gray-800">Privacy</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center pb-4 border-b border-gray-100">
|
||||
<div className="flex items-start">
|
||||
<Search className="h-5 w-5 text-gray-500 mr-2 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-gray-800">Search History</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
Delete all your search history on StudentMarket
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleDeleteHistory("search")}
|
||||
className="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 flex items-center"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-start">
|
||||
<History className="h-5 w-5 text-gray-500 mr-2 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-gray-800">
|
||||
Browsing History
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
Delete all your browsing history on StudentMarket
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleDeleteHistory("browsing")}
|
||||
className="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 flex items-center"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Delete Account (Danger Zone) */}
|
||||
<div className="bg-white border border-red-200 mb-6">
|
||||
<div className="border-b border-red-200 p-4 bg-red-50">
|
||||
<h2 className="text-lg font-medium text-red-700">Danger Zone</h2>
|
||||
<h2 className="text-lg font-medium text-red-700">Danger Zone !!!</h2>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
|
||||
@@ -61,7 +61,7 @@ CREATE TABLE Review (
|
||||
),
|
||||
Date DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (UserID) REFERENCES User (UserID),
|
||||
FOREIGN KEY (ProductID) REFERENCES Product (ProductID)
|
||||
FOREIGN KEY (ProductID) REFERENCES Pprint(item[0])roduct (ProductID)
|
||||
);
|
||||
|
||||
-- Transaction Entity (Many-to-One with User, Many-to-One with Product)
|
||||
@@ -77,16 +77,17 @@ CREATE TABLE Transaction (
|
||||
|
||||
-- Recommendation Entity (Many-to-One with User, Many-to-One with Product)
|
||||
CREATE TABLE Recommendation (
|
||||
RecommendationID_PK INT PRIMARY KEY,
|
||||
RecommendationID_PK INT AUTO_INCREMENT PRIMARY KEY,
|
||||
UserID INT,
|
||||
RecommendedProductID INT,
|
||||
Date DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (UserID) REFERENCES User (UserID),
|
||||
FOREIGN KEY (RecommendedProductID) REFERENCES Product (ProductID)
|
||||
);
|
||||
|
||||
-- History Entity (Many-to-One with User, Many-to-One with Product)
|
||||
CREATE TABLE History (
|
||||
HistoryID INT PRIMARY KEY,
|
||||
HistoryID INT AUTO_INCREMENT PRIMARY KEY,
|
||||
UserID INT,
|
||||
ProductID INT,
|
||||
Date DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
BIN
recommondation-engine/__pycache__/app.cpython-313.pyc
Normal file
BIN
recommondation-engine/__pycache__/app.cpython-313.pyc
Normal file
Binary file not shown.
@@ -4,6 +4,7 @@ import mysql.connector
|
||||
from sklearn.metrics.pairwise import cosine_similarity
|
||||
import numpy as np
|
||||
import logging
|
||||
from unittest import result
|
||||
|
||||
def database():
|
||||
db_connection = mysql.connector.connect(
|
||||
@@ -83,27 +84,57 @@ def get_user_history(user_id):
|
||||
return final
|
||||
|
||||
|
||||
def get_recommendations(user_id, top_n=40):
|
||||
def get_recommendations(user_id, top_n=10):
|
||||
try:
|
||||
# Get all products and user history with their category vectors
|
||||
all_products = get_all_products()
|
||||
user_history = get_user_history(user_id)
|
||||
|
||||
# if not user_history:
|
||||
# # Cold start: return popular products
|
||||
# return get_popular_products(top_n)
|
||||
|
||||
# Calculate similarity between all products and user history
|
||||
user_profile = np.mean(user_history, axis=0) # Average user preferences
|
||||
similarities = cosine_similarity([user_profile], all_products)
|
||||
|
||||
# finds the indices of the top N products that have the highest
|
||||
# cosine similarity with the user's profile and sorted from most similar to least similar.
|
||||
product_indices = similarities[0].argsort()[-top_n:][::-1]
|
||||
print("product", product_indices)
|
||||
|
||||
# Get the recommended product IDs
|
||||
recommended_products = [all_products[i][0] for i in product_indices] # Product IDs
|
||||
|
||||
# Upload the recommendations to the database
|
||||
history_upload(user_id, product_indices) # Pass the indices directly to history_upload
|
||||
|
||||
# Return recommended product IDs
|
||||
return [all_products[i][0] for i in product_indices] # Product IDs
|
||||
return recommended_products
|
||||
except Exception as e:
|
||||
logging.error(f"Recommendation error for user {user_id}: {str(e)}")
|
||||
# return get_popular_products(top_n) # Fallback to popular products
|
||||
|
||||
def history_upload(userID, anrr):
|
||||
db_con = database()
|
||||
cursor = db_con.cursor()
|
||||
|
||||
try:
|
||||
for item in anrr:
|
||||
#Product ID starts form index 1
|
||||
item_value = item + 1
|
||||
print(item_value)
|
||||
# Use parameterized queries to prevent SQL injection
|
||||
cursor.execute(f"INSERT INTO Recommendation (UserID, RecommendedProductID) VALUES ({userID}, {item_value});")
|
||||
|
||||
# Commit the changes
|
||||
db_con.commit()
|
||||
|
||||
# If you need results, you'd typically fetch them after a SELECT query
|
||||
# results = cursor.fetchall()
|
||||
# print(results)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
db_con.rollback()
|
||||
finally:
|
||||
# Close the cursor and connection
|
||||
cursor.close()
|
||||
db_con.close()
|
||||
@@ -1,6 +1,8 @@
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
from example1 import get_recommendations
|
||||
from app import get_recommendations
|
||||
from app import history_upload
|
||||
|
||||
import time
|
||||
|
||||
|
||||
@@ -18,8 +20,7 @@ def handle_session_data():
|
||||
if not user_id or not email or is_authenticated is None:
|
||||
return jsonify({'error': 'Invalid data'}), 400
|
||||
|
||||
print(get_recommendations(user_id))
|
||||
time.sleep(2)
|
||||
get_recommendations(user_id)
|
||||
|
||||
print(f"Received session data: User ID: {user_id}, Email: {email}, Authenticated: {is_authenticated}")
|
||||
return jsonify({'message': 'Session data received successfully'})
|
||||
|
||||
Reference in New Issue
Block a user