-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
694 lines (602 loc) · 30.7 KB
/
Copy pathapp.py
File metadata and controls
694 lines (602 loc) · 30.7 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
from flask import Flask, request, render_template, session, redirect, url_for, jsonify
import pandas as pd
import numpy as np
import random
import json
import re
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from groq import Groq
from dotenv import load_dotenv
load_dotenv()
import os
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
GROQ_MODEL = "llama-3.3-70b-versatile"
groq_client = Groq(api_key=GROQ_API_KEY)
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY", "alskdjfwoeieiurlskdjfslkdjf")
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///ecom.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# ── Load data ─────────────────────────────────────────────────
trending_products = pd.read_csv("models/trending_products.csv")
train_data = pd.read_csv("models/clean_data.csv")
train_data['ImageURL'] = train_data['ImageURL'].astype(str).apply(
lambda x: x.split('|')[0].strip()
)
train_data['Rating'] = pd.to_numeric(train_data['Rating'], errors='coerce').fillna(0)
train_data['Rating'] = train_data['Rating'].apply(lambda x: 0 if x == -2147483648 else x)
train_data['ReviewCount'] = pd.to_numeric(train_data['ReviewCount'], errors='coerce').fillna(0)
train_data['ReviewCount'] = train_data['ReviewCount'].apply(lambda x: 0 if x == -2147483648 else x)
# ── Models ────────────────────────────────────────────────────
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)
class Order(db.Model):
__tablename__ = 'orders'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
order_id = db.Column(db.String(50), nullable=False)
items = db.Column(db.Text, nullable=False)
total = db.Column(db.Float, nullable=False)
payment_method = db.Column(db.String(100), nullable=False)
delivery_name = db.Column(db.String(200), nullable=False)
delivery_address = db.Column(db.String(500), nullable=False)
placed_at = db.Column(db.DateTime, default=datetime.utcnow)
def items_list(self):
try:
return json.loads(self.items)
except Exception:
return []
# ── Constants ─────────────────────────────────────────────────
random_image_urls = [
"static/img/img1.jpg", "static/img/img2.jpg",
"static/img/img3.jpg", "static/img/img4.jpg",
"static/img/img5.jpg", "static/img/img6.jpg",
"static/img/img7.jpg", "static/img/img8.jpg",
]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
# ── Utility functions ─────────────────────────────────────────
def truncate(text, length):
return text[:length] + "..." if len(text) > length else text
def _resolve_image(url_val):
url = str(url_val).strip()
if url.startswith('http://') or url.startswith('https://'):
return url
if url.startswith('static/'):
return '/' + url
if url.startswith('/static/'):
return url
return 'https://placehold.co/300x220/f5a623/ffffff?text=Product'
def _df_to_products(df, limit=6):
result = []
for _, row in df.head(limit).iterrows():
try:
r = float(row.get('Rating', 0))
rating_str = str(round(r, 1)) if r > 0 else 'N/A'
except Exception:
rating_str = 'N/A'
result.append({
'name': str(row.get('Name', 'Product')),
'brand': str(row.get('Brand', 'N/A')),
'image': _resolve_image(row.get('ImageURL', '')),
'rating': rating_str,
'price': random.choice(price)
})
return result
def session_vars():
cart = session.get('cart', [])
return {
'logged_in': session.get('logged_in', False),
'username': session.get('username', ''),
'cart_count': sum(i['quantity'] for i in cart),
'cart': cart,
}
# ── Recommendation engine ─────────────────────────────────────
def content_based_recommendations(train_data, item_name, top_n=8):
if 'Name' not in train_data.columns:
return pd.DataFrame()
matches = train_data[
train_data['Name'].astype(str).str.lower().str.contains(item_name.lower(), na=False)
]
if matches.empty:
return pd.DataFrame()
matched_name = matches.iloc[0]['Name']
tfidf_data = train_data.copy()
tfidf_data['Tags'] = tfidf_data['Tags'].fillna('') + " " + tfidf_data['Name'].fillna('')
tfidf_vectorizer = TfidfVectorizer(stop_words='english')
tfidf_matrix = tfidf_vectorizer.fit_transform(tfidf_data['Tags'])
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
match_mask = tfidf_data['Name'].astype(str).str.lower().str.contains(matched_name.lower(), na=False)
if not match_mask.any():
return pd.DataFrame()
item_pos = tfidf_data.index.get_loc(tfidf_data[match_mask].index[0])
similar = sorted(enumerate(cosine_sim[item_pos]), key=lambda x: x[1], reverse=True)
top_indices = [x[0] for x in similar[1:top_n + 1]]
return tfidf_data.iloc[top_indices][['Name', 'ReviewCount', 'Brand', 'ImageURL', 'Rating']]
def collaborative_filtering_recommendations(train_data, target_product_name, top_n=4):
try:
df = train_data.copy()
df['Name'] = df['Name'].fillna('')
df['Tags'] = df['Tags'].fillna('')
df['Brand'] = df['Brand'].fillna('Unknown')
df['Rating'] = pd.to_numeric(df['Rating'], errors='coerce').fillna(0)
df['ReviewCount'] = pd.to_numeric(df['ReviewCount'], errors='coerce').fillna(0)
cat_col = next((c for c in ['Category','category','ProductType','Type'] if c in df.columns), None)
matches = df[df['Name'].str.lower().str.contains(target_product_name.lower(), na=False)]
if matches.empty:
return pd.DataFrame()
seed_row = matches.iloc[0]
seed_name = seed_row['Name']
seed_cat = seed_row[cat_col] if cat_col else None
df['combined'] = df['Tags'] + " " + df['Name']
tfidf_matrix = TfidfVectorizer(stop_words='english', max_features=8000).fit_transform(df['combined'])
seed_mask = df['Name'].str.lower().str.contains(seed_name.lower(), na=False)
seed_loc = df.index.get_loc(df[seed_mask].index[0])
content_scores = cosine_similarity(tfidf_matrix[seed_loc], tfidf_matrix).flatten()
collab_scores = np.zeros(len(df))
try:
cat_df = df[df[cat_col] == seed_cat].copy() if cat_col and seed_cat \
else df.sample(min(8000, len(df)), random_state=42).copy()
if len(cat_df) > 1:
cat_df['RatingBucket'] = pd.cut(
cat_df['Rating'], bins=[0,1,2,3,4,5],
labels=['r1','r2','r3','r4','r5'], include_lowest=True
).astype(str)
cat_df = cat_df.drop_duplicates(subset=['Name'])
pivot = cat_df.pivot_table(index='Name', columns='RatingBucket',
values='ReviewCount', aggfunc='sum', fill_value=0)
if seed_name in pivot.index and len(pivot) > 1:
sim_row = cosine_similarity(pivot)[pivot.index.tolist().index(seed_name)]
name_to_sim = dict(zip(pivot.index.tolist(), sim_row))
collab_scores = np.array([name_to_sim.get(n, 0.0) for n in df['Name']])
except Exception:
pass
c_max = collab_scores.max()
collab_norm = collab_scores / (c_max + 1e-9)
content_norm = content_scores / (content_scores.max() + 1e-9)
blended = (0.60 * collab_norm + 0.40 * content_norm) if c_max > 0.01 \
else (0.55 * content_norm + 0.45 * df['Rating'].values / (df['Rating'].max() + 1e-9))
blended[seed_loc] = -1
seen, final = set(), []
for idx in np.argsort(blended)[::-1][:top_n * 4]:
name = df.iloc[idx]['Name']
if name not in seen and name.lower() != seed_name.lower():
seen.add(name); final.append(idx)
if len(final) >= top_n:
break
return df.iloc[final][['Name', 'ReviewCount', 'Brand', 'ImageURL', 'Rating']] if final \
else pd.DataFrame()
except Exception as e:
print(f"Collab error: {e}")
return pd.DataFrame()
# ── Groq / ShopBot ────────────────────────────────────────────
def _build_catalog():
try:
brands = train_data['Brand'].dropna().unique().tolist()[:80]
samples = train_data['Name'].dropna().sample(min(50, len(train_data)), random_state=1).tolist()
trending = trending_products['Name'].dropna().tolist()[:10]
return (f"Brands: {', '.join(str(b) for b in brands)}.\n"
f"Sample products: {', '.join(str(n) for n in samples)}.\n"
f"Trending: {', '.join(str(n) for n in trending)}.")
except Exception:
return "Beauty and cosmetics ecommerce store."
CATALOG = _build_catalog()
SYSTEM_PROMPT = f"""You are ShopBot, a smart shopping assistant for a beauty and cosmetics store.
Rules:
- Be warm, brief and helpful. Max 2 sentences for your reply text.
- When the user wants products, you MUST output a SEARCH_KEYWORD line at the end.
- SEARCH_KEYWORD tells the backend what to search. Be specific. Use ONE or TWO words only.
- For greetings/casual chat, do NOT output SEARCH_KEYWORD.
Store catalog: {CATALOG}
SEARCH_KEYWORD rules:
- User wants lipstick → SEARCH_KEYWORD: lipstick
- User wants trending/popular → SEARCH_KEYWORD: TRENDING
- User wants top rated → SEARCH_KEYWORD: TOP_RATED
- User has oily skin → SEARCH_KEYWORD: moisturizer
- User has acne / pimples → SEARCH_KEYWORD: salicylic
- User has dandruff → SEARCH_KEYWORD: anti dandruff
- User wants anti aging → SEARCH_KEYWORD: retinol
- User wants glow / brightening → SEARCH_KEYWORD: vitamin c
- User says hi/thanks/bye → no SEARCH_KEYWORD
IMPORTANT: SEARCH_KEYWORD must be a real product name or ingredient — NOT a sentence or price range.
Format: always put SEARCH_KEYWORD: <word> on its own line at the very end."""
# ── Skin / hair / concern → searchable keyword map ────────────
CONCERN_MAP = {
'oily skin': 'moisturizer',
'oily': 'oil control',
'dry skin': 'moisturizer',
'dry': 'moisturizer',
'sensitive skin': 'sensitive',
'sensitive': 'gentle',
'combination skin': 'moisturizer',
'normal skin': 'moisturizer',
'acne': 'salicylic',
'pimple': 'salicylic',
'pimples': 'salicylic',
'dark spot': 'serum',
'dark spots': 'brightening',
'blackhead': 'charcoal',
'blackheads': 'pore',
'wrinkle': 'retinol',
'wrinkles': 'retinol',
'anti aging': 'retinol',
'anti-aging': 'retinol',
'brightening': 'vitamin c',
'glow': 'serum',
'glowing skin': 'serum',
'dull skin': 'exfoliating',
'pigmentation': 'vitamin c',
'redness': 'calming',
'sunburn': 'aloe',
'tan': 'sunscreen',
'sun protection': 'sunscreen',
'spf': 'sunscreen',
'hair loss': 'biotin',
'hair fall': 'hair growth',
'dandruff': 'anti dandruff',
'frizzy hair': 'smoothing',
'frizzy': 'smoothing',
'curly hair': 'curl',
'dry hair': 'conditioner',
'oily hair': 'shampoo',
'damaged hair': 'repair',
'body odor': 'deodorant',
'rough skin': 'body lotion',
'cracked heels': 'foot cream',
}
# ── Strip filler words and prices from Groq keyword ───────────
_STRIP_WORDS = re.compile(
r'\b(products?|items?|brands?|under|below|less than|up to|upto|'
r'cheaper than|above|over|more than|for|with|and|or|the|a|an|'
r'good|best|top|great|nice|cheap|affordable|budget|premium|'
r'recommend|suggest|find|show|give|get)\b',
re.IGNORECASE
)
_PRICE_RE = re.compile(r'\$?\d+', re.IGNORECASE)
def _clean_keyword(raw):
"""
Translate Groq keyword to something the engine can find.
e.g. 'oil control products under 50' → 'oil control'
'oily skin moisturizer' → 'moisturizer'
'acne prone skin' → 'salicylic'
"""
kw = raw.strip().lower()
# 1. Map skin/hair concerns first
for concern, mapped in CONCERN_MAP.items():
if concern in kw:
return mapped
# 2. Strip price amounts
kw = _PRICE_RE.sub('', kw)
# 3. Strip filler words
kw = _STRIP_WORDS.sub(' ', kw)
# 4. Collapse whitespace
kw = ' '.join(kw.split()).strip()
return kw if kw else raw.strip()
# ── Product fetcher with 5-step fallback chain ────────────────
def _fetch_products(keyword, logged_in):
raw_keyword = keyword.strip()
clean_kw = _clean_keyword(raw_keyword)
# Special keywords
if raw_keyword.upper() == 'TRENDING':
result = []
for _, row in trending_products.head(6).iterrows():
result.append({
'name': str(row.get('Name', 'Product')),
'brand': str(row.get('Brand', 'N/A')),
'image': _resolve_image(row.get('ImageURL', '')),
'rating': str(row.get('Rating', 'N/A')),
'price': random.choice(price)
})
return result
if raw_keyword.upper() == 'TOP_RATED':
return _df_to_products(train_data.sort_values('Rating', ascending=False).head(6))
# Step 1: content-based on cleaned keyword
recs = content_based_recommendations(train_data, clean_kw, top_n=6)
# Step 2: blend collab for logged-in users
if logged_in and not recs.empty:
collab = collaborative_filtering_recommendations(train_data, clean_kw, top_n=3)
if not collab.empty:
existing = set(recs['Name'].tolist())
collab = collab[~collab['Name'].isin(existing)]
recs = pd.concat([recs, collab]).head(8)
if not recs.empty:
return _df_to_products(recs)
# Step 3: brand search
brand_results = train_data[
train_data['Brand'].astype(str).str.lower()
.str.contains(clean_kw.lower(), na=False)
].head(6)
if not brand_results.empty:
return _df_to_products(brand_results)
# Step 4: partial name search
name_results = train_data[
train_data['Name'].astype(str).str.lower()
.str.contains(clean_kw.lower(), na=False)
].head(6)
if not name_results.empty:
return _df_to_products(name_results)
# Step 5: graceful fallback — top rated (never return empty)
return _df_to_products(train_data.sort_values('Rating', ascending=False).head(6))
# ═══════════════════════════════════════════════════════════════
# CHAT ROUTE
# ═══════════════════════════════════════════════════════════════
@app.route('/chat', methods=['POST'])
def chat():
data = request.get_json()
user_msg = (data.get('message') or '').strip()
if not user_msg:
return jsonify({'reply': "Say something and I'll help! 🛍️", 'products': []})
username = session.get('username', '')
logged_in = session.get('logged_in', False)
history = session.get('chat_history', [])
history.append({"role": "user", "content": user_msg})
if len(history) > 6:
history = history[-6:]
products = []
reply = ''
try:
system = SYSTEM_PROMPT
if username:
system += f"\n\nUser's name is {username}. Address them by name once when greeting."
response = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[{"role": "system", "content": system}] + history,
temperature=0.4,
max_tokens=200,
)
full_text = response.choices[0].message.content.strip()
search_keyword = None
if 'SEARCH_KEYWORD:' in full_text:
parts = full_text.split('SEARCH_KEYWORD:')
reply = parts[0].strip()
search_keyword = parts[1].strip().split('\n')[0].strip()
else:
reply = full_text
if search_keyword:
products = _fetch_products(search_keyword, logged_in)
# ✅ No "Couldn't find..." — fallback chain always returns products
history.append({"role": "assistant", "content": full_text})
session['chat_history'] = history[-6:]
session.modified = True
except Exception as e:
print(f"[Groq ERROR]: {type(e).__name__}: {e}")
reply = "Something went wrong. Please try again! 😊"
products = []
return jsonify({'reply': reply, 'products': products})
# ═══════════════════════════════════════════════════════════════
# CART ROUTES
# ═══════════════════════════════════════════════════════════════
@app.route('/add_to_cart', methods=['POST'])
def add_to_cart():
data = request.get_json()
name = (data.get('name') or '').strip()
if not name:
return jsonify({'success': False, 'message': 'Invalid product'}), 400
cart = session.get('cart', [])
for item in cart:
if item['name'] == name:
item['quantity'] += 1
session['cart'] = cart; session.modified = True
return jsonify({'success': True,
'cart_count': sum(i['quantity'] for i in cart),
'message': 'Quantity updated!'})
cart.append({'name': name, 'brand': data.get('brand', 'N/A'),
'image': data.get('image', ''), 'rating': data.get('rating', 'N/A'),
'price': data.get('price', 50), 'quantity': 1})
session['cart'] = cart; session.modified = True
return jsonify({'success': True,
'cart_count': sum(i['quantity'] for i in cart),
'message': f'"{truncate(name, 25)}" added to cart!'})
@app.route('/update_cart', methods=['POST'])
def update_cart():
data = request.get_json()
name = data.get('name', ''); action = data.get('action', '')
cart = session.get('cart', [])
for item in cart:
if item['name'] == name:
if action == 'increase':
item['quantity'] += 1
elif action == 'decrease':
item['quantity'] -= 1
if item['quantity'] <= 0:
cart.remove(item)
break
session['cart'] = cart; session.modified = True
total = sum(i['price'] * i['quantity'] for i in cart)
return jsonify({'success': True,
'cart_count': sum(i['quantity'] for i in cart),
'total': round(total, 2)})
@app.route('/remove_from_cart', methods=['POST'])
def remove_from_cart():
data = request.get_json()
cart = [i for i in session.get('cart', []) if i['name'] != data.get('name', '')]
session['cart'] = cart; session.modified = True
total = sum(i['price'] * i['quantity'] for i in cart)
return jsonify({'success': True,
'cart_count': sum(i['quantity'] for i in cart),
'total': round(total, 2)})
@app.route('/cart')
def cart_page():
cart = session.get('cart', [])
total = sum(i['price'] * i['quantity'] for i in cart)
return render_template('cart.html', total=round(total, 2), **session_vars())
# ═══════════════════════════════════════════════════════════════
# SAVE ORDER
# ═══════════════════════════════════════════════════════════════
@app.route('/save_order', methods=['POST'])
def save_order():
username = session.get('username', 'guest') if session.get('logged_in') else 'guest'
data = request.get_json()
cart = session.get('cart', [])
if not cart:
return jsonify({'success': False, 'message': 'Cart is empty'})
try:
order = Order(
username = username,
order_id = data.get('order_id', 'ORD000000'),
items = json.dumps(cart),
total = float(data.get('total', 0)),
payment_method = data.get('payment_method', 'Unknown'),
delivery_name = data.get('delivery_name', ''),
delivery_address = data.get('delivery_address', ''),
)
db.session.add(order)
db.session.commit()
session['cart'] = []
session.modified = True
return jsonify({'success': True, 'order_id': order.order_id})
except Exception as e:
print(f"[save_order ERROR]: {e}")
return jsonify({'success': False, 'message': str(e)})
# ═══════════════════════════════════════════════════════════════
# ORDER HISTORY
# ═══════════════════════════════════════════════════════════════
@app.route('/orders')
def order_history():
if not session.get('logged_in'):
return redirect(url_for('index'))
username = session.get('username')
orders = Order.query.filter_by(username=username)\
.order_by(Order.placed_at.desc()).all()
return render_template('order_history.html', orders=orders, **session_vars())
# ═══════════════════════════════════════════════════════════════
# PAGE ROUTES
# ═══════════════════════════════════════════════════════════════
def _imgs():
return [random_image_urls[i % len(random_image_urls)] for i in range(len(trending_products))]
@app.route("/")
def index():
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
**session_vars())
@app.route("/main")
def main():
return render_template('main.html',
content_based_rec=pd.DataFrame(),
collab_rec=pd.DataFrame(),
truncate=truncate,
random_price=random.choice(price),
**session_vars())
@app.route("/index")
def indexredirect():
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
**session_vars())
@app.route("/signup", methods=['POST', 'GET'])
def signup():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
if Signup.query.filter_by(username=username).first():
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
signup_message='Username already exists! Please Sign In.',
signup_error=True, open_signin=True, **session_vars())
db.session.add(Signup(username=username, email=email, password=password))
db.session.commit()
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
signup_message='Account created! Please Sign In.',
open_signin=True, **session_vars())
return redirect(url_for('index'))
@app.route('/signin', methods=['POST', 'GET'])
def signin():
if request.method == 'POST':
username = request.form['signinUsername']
password = request.form['signinPassword']
user = Signup.query.filter_by(username=username, password=password).first()
if user:
session['logged_in'] = True
session['username'] = username
cart = session.get('cart', [])
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
signup_message=f'Welcome back, {username}!',
logged_in=True, username=username,
cart_count=sum(i['quantity'] for i in cart),
cart=cart)
user_exists = Signup.query.filter_by(username=username).first()
msg = 'Account not found! Please Sign Up.' if not user_exists else 'Incorrect password!'
return render_template('index.html',
trending_products=trending_products.head(8),
truncate=truncate,
random_product_image_urls=_imgs(),
random_price=random.choice(price),
signup_message=msg,
signin_error=True, open_signin=True, **session_vars())
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@app.route("/recommendations", methods=['POST', 'GET'])
def recommendations():
if request.method == 'POST':
prod = (request.form.get('prod') or '').strip()
if not prod:
return render_template('main.html',
message="Please enter a product name.",
content_based_rec=pd.DataFrame(),
collab_rec=pd.DataFrame(),
truncate=truncate,
random_price=random.choice(price),
**session_vars())
content_based_rec = content_based_recommendations(train_data, prod, top_n=6)
collab_rec = pd.DataFrame()
# ✅ Logged in → hybrid (content + collab)
# ✅ Guest → content-based only
if session.get('logged_in'):
collab_rec = collaborative_filtering_recommendations(train_data, prod, top_n=4)
if not content_based_rec.empty and not collab_rec.empty:
content_names = set(content_based_rec['Name'].tolist())
collab_rec = collab_rec[~collab_rec['Name'].isin(content_names)]
if content_based_rec.empty:
return render_template('main.html',
message=f"No results for '{prod}'. Try another keyword.",
content_based_rec=pd.DataFrame(),
collab_rec=pd.DataFrame(),
truncate=truncate,
random_price=random.choice(price),
**session_vars())
return render_template('main.html',
content_based_rec=content_based_rec,
collab_rec=collab_rec,
truncate=truncate,
random_price=random.choice(price),
**session_vars())
return render_template('main.html',
content_based_rec=pd.DataFrame(),
collab_rec=pd.DataFrame(),
truncate=truncate,
random_price=random.choice(price),
**session_vars())
@app.route('/payment')
def payment():
cart = session.get('cart', [])
total = sum(i['price'] * i['quantity'] for i in cart)
return render_template('payment.html', total=int(total * 1.08), **session_vars())
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(debug=True)