-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapp.py
174 lines (141 loc) · 7.5 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
from flask import Flask, request, render_template
import pandas as pd
import random
from flask_sqlalchemy import SQLAlchemy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
# load files===========================================================================================================
trending_products = pd.read_csv("models/trending_products.csv")
train_data = pd.read_csv("models/clean_data.csv")
# database configuration---------------------------------------
app.secret_key = "alskdjfwoeieiurlskdjfslkdjf"
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:@localhost/ecom"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Define your model class for the 'signup' table
class Signup(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(100), nullable=False)
# Define your model class for the 'signup' table
class Signin(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(100), nullable=False)
# Recommendations functions============================================================================================
# Function to truncate product name
def truncate(text, length):
if len(text) > length:
return text[:length] + "..."
else:
return text
def content_based_recommendations(train_data, item_name, top_n=10):
# Check if the item name exists in the training data
if item_name not in train_data['Name'].values:
print(f"Item '{item_name}' not found in the training data.")
return pd.DataFrame()
# Create a TF-IDF vectorizer for item descriptions
tfidf_vectorizer = TfidfVectorizer(stop_words='english')
# Apply TF-IDF vectorization to item descriptions
tfidf_matrix_content = tfidf_vectorizer.fit_transform(train_data['Tags'])
# Calculate cosine similarity between items based on descriptions
cosine_similarities_content = cosine_similarity(tfidf_matrix_content, tfidf_matrix_content)
# Find the index of the item
item_index = train_data[train_data['Name'] == item_name].index[0]
# Get the cosine similarity scores for the item
similar_items = list(enumerate(cosine_similarities_content[item_index]))
# Sort similar items by similarity score in descending order
similar_items = sorted(similar_items, key=lambda x: x[1], reverse=True)
# Get the top N most similar items (excluding the item itself)
top_similar_items = similar_items[1:top_n+1]
# Get the indices of the top similar items
recommended_item_indices = [x[0] for x in top_similar_items]
# Get the details of the top similar items
recommended_items_details = train_data.iloc[recommended_item_indices][['Name', 'ReviewCount', 'Brand', 'ImageURL', 'Rating']]
return recommended_items_details
# routes===============================================================================
# List of predefined image URLs
random_image_urls = [
"static/img/img_1.png",
"static/img/img_2.png",
"static/img/img_3.png",
"static/img/img_4.png",
"static/img/img_5.png",
"static/img/img_6.png",
"static/img/img_7.png",
"static/img/img_8.png",
]
@app.route("/")
def index():
# Create a list of random image URLs for each product
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(trending_products))]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('index.html',trending_products=trending_products.head(8),truncate = truncate,
random_product_image_urls=random_product_image_urls,
random_price = random.choice(price))
@app.route("/main")
def main():
return render_template('main.html')
# routes
@app.route("/index")
def indexredirect():
# Create a list of random image URLs for each product
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(trending_products))]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('index.html', trending_products=trending_products.head(8), truncate=truncate,
random_product_image_urls=random_product_image_urls,
random_price=random.choice(price))
@app.route("/signup", methods=['POST','GET'])
def signup():
if request.method=='POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
new_signup = Signup(username=username, email=email, password=password)
db.session.add(new_signup)
db.session.commit()
# Create a list of random image URLs for each product
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(trending_products))]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('index.html', trending_products=trending_products.head(8), truncate=truncate,
random_product_image_urls=random_product_image_urls, random_price=random.choice(price),
signup_message='User signed up successfully!'
)
# Route for signup page
@app.route('/signin', methods=['POST', 'GET'])
def signin():
if request.method == 'POST':
username = request.form['signinUsername']
password = request.form['signinPassword']
new_signup = Signin(username=username,password=password)
db.session.add(new_signup)
db.session.commit()
# Create a list of random image URLs for each product
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(trending_products))]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('index.html', trending_products=trending_products.head(8), truncate=truncate,
random_product_image_urls=random_product_image_urls, random_price=random.choice(price),
signup_message='User signed in successfully!'
)
@app.route("/recommendations", methods=['POST', 'GET'])
def recommendations():
if request.method == 'POST':
prod = request.form.get('prod')
nbr = int(request.form.get('nbr'))
content_based_rec = content_based_recommendations(train_data, prod, top_n=nbr)
if content_based_rec.empty:
message = "No recommendations available for this product."
return render_template('main.html', message=message)
else:
# Create a list of random image URLs for each recommended product
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(trending_products))]
print(content_based_rec)
print(random_product_image_urls)
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('main.html', content_based_rec=content_based_rec, truncate=truncate,
random_product_image_urls=random_product_image_urls,
random_price=random.choice(price))
if __name__=='__main__':
app.run(debug=True)