-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAI_E-Commerce_Complete_Guide.html
More file actions
1836 lines (1719 loc) · 61.1 KB
/
AI_E-Commerce_Complete_Guide.html
File metadata and controls
1836 lines (1719 loc) · 61.1 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI E-Commerce Recommendation Engine - Complete Guide</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
line-height: 1.6;
color: #333;
max-width: 1000px;
margin: 0 auto;
padding: 40px 20px;
background-color: #fff;
}
h1 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 15px;
margin-top: 40px;
font-size: 2.5em;
}
h2 {
color: #2c3e50;
border-bottom: 2px solid #bdc3c7;
padding-bottom: 10px;
margin-top: 35px;
font-size: 2em;
}
h3 {
color: #34495e;
margin-top: 30px;
font-size: 1.5em;
}
h4 {
color: #34495e;
margin-top: 25px;
font-size: 1.2em;
}
p {
margin-bottom: 16px;
text-align: justify;
}
code {
background-color: #f8f9fa;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
font-size: 0.9em;
color: #e74c3c;
}
pre {
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 20px;
overflow-x: auto;
margin: 20px 0;
border-left: 4px solid #3498db;
}
pre code {
background-color: transparent;
padding: 0;
color: #2c3e50;
}
blockquote {
border-left: 4px solid #3498db;
margin: 20px 0;
padding-left: 20px;
color: #666;
font-style: italic;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
th, td {
border: 1px solid #ddd;
padding: 12px 15px;
text-align: left;
}
th {
background-color: #3498db;
color: white;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
ul, ol {
margin-bottom: 16px;
padding-left: 30px;
}
li {
margin-bottom: 8px;
}
.toc {
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 20px;
margin: 30px 0;
}
.toc h2 {
margin-top: 0;
color: #2c3e50;
border-bottom: 1px solid #bdc3c7;
}
.toc ul {
list-style-type: none;
padding-left: 0;
}
.toc ul ul {
padding-left: 20px;
}
.toc a {
color: #3498db;
text-decoration: none;
}
.toc a:hover {
text-decoration: underline;
}
.highlight {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 4px;
padding: 15px;
margin: 20px 0;
}
.note {
background-color: #d1ecf1;
border: 1px solid #bee5eb;
border-radius: 4px;
padding: 15px;
margin: 20px 0;
}
.warning {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 4px;
padding: 15px;
margin: 20px 0;
}
@media print {
body {
margin: 0;
padding: 20px;
font-size: 12pt;
}
h1 {
page-break-before: always;
font-size: 18pt;
}
h2 {
page-break-before: avoid;
font-size: 16pt;
}
h3 {
font-size: 14pt;
}
pre, code {
page-break-inside: avoid;
}
table {
page-break-inside: avoid;
}
.toc {
page-break-after: always;
}
}
</style>
</head>
<body>
<h1>🚀 AI E-Commerce Recommendation Engine - Complete Technical Documentation</h1>
<br>
<h2>Table of Contents</h2>
<li>[Project Overview](#project-overview)</li>
<p>2. [Architecture & System Design](#architecture--system-design)</p>
<p>3. [Backend Technologies](#backend-technologies)</p>
<p>4. [Frontend Technologies](#frontend-technologies)</p>
<p>5. [Machine Learning Components](#machine-learning-components)</p>
<p>6. [Database Design](#database-design)</p>
<p>7. [API Endpoints](#api-endpoints)</p>
<p>8. [Deployment & DevOps](#deployment--devops)</p>
<p>9. [Code Structure & Files](#code-structure--files)</p>
<p>10. [How Everything Works Together](#how-everything-works-together)</p>
<p>11. [Learning Path & Next Steps](#learning-path--next-steps)</p>
<br>
<p>---</p>
<br>
<h2>1. Project Overview</h2>
<br>
<h3>What is this project?</h3>
<p>This is a <strong>full-stack AI-powered e-commerce recommendation engine<strong> that provides personalized product recommendations to users based on their behavior, preferences, and interaction history.</p>
<br>
<h3>Key Features</h3>
<li>**AI-Powered Recommendations**: Uses machine learning algorithms to suggest products</li>
<li>**Real-time User Tracking**: Records and analyzes user interactions</li>
<li>**RESTful API**: Clean, well-documented API endpoints</li>
<li>**Admin Dashboard**: Django admin interface for data management</li>
<li>**React Frontend**: Modern, responsive user interface</li>
<li>**Scalable Architecture**: Designed for production deployment</li>
<br>
<h3>Technologies Stack Overview</h3>
<pre><code class="">
Frontend: React 18 + JavaScript + CSS
Backend: Django 4.2 + Python 3.10 + Django REST Framework
Database: SQLite (dev) / PostgreSQL (prod)
Cache: Redis (optional)
ML Libraries: scikit-learn, pandas, numpy
Deployment: Docker + Docker Compose
</code></pre>
<br>
<p>---</p>
<br>
<h2>2. Architecture & System Design</h2>
<br>
<h3>High-Level Architecture</h3>
<pre><code class="">
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ React Frontend │ │ Django API │ │ ML Engine │
│ (Port 3000) │◄──►│ (Port 8000) │◄──►│ (scikit-learn) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ SQLite DB │ │
│ │ (Users, Prods, │ │
│ │ Interactions) │ │
│ └─────────────────┘ │
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ Cache Layer (Redis - Optional) │
└─────────────────────────────────────────────────────────────┘
</code></pre>
<br>
<h3>Request Flow</h3>
<li>**User Interaction**: User clicks/views product in React frontend</li>
<p>2. <strong>API Request<strong>: Frontend sends HTTP request to Django backend</p>
<p>3. <strong>Business Logic<strong>: Django processes request, applies business rules</p>
<p>4. <strong>ML Processing<strong>: Recommendation engine generates personalized suggestions</p>
<p>5. <strong>Database Query<strong>: Data retrieved/stored in SQLite database</p>
<p>6. <strong>Response<strong>: JSON data sent back to frontend</p>
<p>7. <strong>UI Update<strong>: React updates interface with new data</p>
<br>
<p>---</p>
<br>
<h2>3. Backend Technologies</h2>
<br>
<h3>3.1 Django Framework</h3>
<p><strong>What it is<strong>: Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.</p>
<br>
<p><strong>Why we use it<strong>:</p>
<li>**ORM (Object-Relational Mapping)**: Simplifies database operations</li>
<li>**Admin Interface**: Automatic admin panel for data management</li>
<li>**Security**: Built-in protection against common vulnerabilities</li>
<li>**Scalability**: Handles high traffic efficiently</li>
<br>
<p><strong>Key Django Components in Our Project<strong>:</p>
<br>
<h4>3.1.1 Models (`recommendations/models.py`)</h4>
<pre><code class="python">
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
category = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
</code></pre>
<p><strong>Explanation<strong>: Models define database table structure using Python classes.</p>
<br>
<h4>3.1.2 Views (`recommendations/views.py`)</h4>
<pre><code class="python">
class RecommendationsAPIView(APIView):
def get(self, request, user_id):
# Get personalized recommendations
recommendations = recommendation_engine.get_recommendations(user_id)
return Response(recommendations)
</code></pre>
<p><strong>Explanation<strong>: Views handle HTTP requests and return responses.</p>
<br>
<h4>3.1.3 URLs (`recommendations/urls.py`)</h4>
<pre><code class="python">
urlpatterns = [
path('recommendations/<int:user_id>/', views.RecommendationsAPIView.as_view()),
path('interaction/', views.InteractionAPIView.as_view()),
]
</code></pre>
<p><strong>Explanation<strong>: URLs route incoming requests to appropriate views.</p>
<br>
<h3>3.2 Django REST Framework (DRF)</h3>
<p><strong>What it is<strong>: A powerful toolkit for building Web APIs in Django.</p>
<br>
<p><strong>Features we use<strong>:</p>
<li>**Serializers**: Convert complex data types to JSON</li>
<li>**ViewSets**: Organize view logic</li>
<li>**Permissions**: Control API access</li>
<li>**Pagination**: Handle large datasets efficiently</li>
<br>
<p><strong>Example Serializer<strong>:</p>
<pre><code class="python">
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'category', 'price', 'description']
</code></pre>
<br>
<h3>3.3 Database Layer</h3>
<br>
<h4>SQLite (Development)</h4>
<li>**File-based database**: Stored in `db.sqlite3`</li>
<li>**No server required**: Perfect for development</li>
<li>**ACID compliant**: Ensures data integrity</li>
<li>**Zero configuration**: Works out of the box</li>
<br>
<h4>PostgreSQL (Production)</h4>
<li>**Production-grade**: Handles millions of records</li>
<li>**Advanced features**: Full-text search, JSON support</li>
<li>**Scalable**: Supports read replicas, sharding</li>
<li>**ACID compliant**: Enterprise-level data integrity</li>
<br>
<h3>3.4 Caching with Redis (Optional)</h3>
<p><strong>What it is<strong>: In-memory data structure store used as cache.</p>
<br>
<p><strong>How we use it<strong>:</p>
<pre><code class="python">
from django.core.cache import cache
# Store recommendations in cache
cache.set(f'recommendations_user_{user_id}', recommendations, timeout=1800)
# Retrieve from cache
cached_data = cache.get(f'recommendations_user_{user_id}')
</code></pre>
<br>
<p><strong>Benefits<strong>:</p>
<li>**Speed**: Sub-millisecond response times</li>
<li>**Reduced database load**: Fewer queries to database</li>
<li>**Scalability**: Handles high concurrent users</li>
<br>
<p>---</p>
<br>
<h2>4. Frontend Technologies</h2>
<br>
<h3>4.1 React 18</h3>
<p><strong>What it is<strong>: A JavaScript library for building user interfaces.</p>
<br>
<p><strong>Why React<strong>:</p>
<li>**Component-Based**: Reusable UI components</li>
<li>**Virtual DOM**: Efficient rendering</li>
<li>**State Management**: Reactive data flow</li>
<li>**Large Ecosystem**: Extensive package library</li>
<br>
<h3>4.2 Key React Concepts in Our Project</h3>
<br>
<h4>4.2.1 Components (`frontend/src/App.js`)</h4>
<pre><code class="javascript">
const ProductCard = ({ product, isRecommendation = false }) => (
<div className="product-card">
<h3>{product.name}</h3>
<p>{product.category}</p>
<span>${product.price}</span>
{isRecommendation && (
<div className="ai-score">
AI Score: {Math.round(product.confidence_score * 100)}%
</div>
)}
</div>
);
</code></pre>
<br>
<h4>4.2.2 State Management</h4>
<pre><code class="javascript">
const [recommendations, setRecommendations] = useState([]);
const [loading, setLoading] = useState(false);
const [currentUser, setCurrentUser] = useState(null);
</code></pre>
<br>
<h4>4.2.3 API Integration</h4>
<pre><code class="javascript">
const fetchRecommendations = async (userId) => {
setLoading(true);
try {
const response = await fetch(`/api/recommendations/${userId}/`);
const data = await response.json();
setRecommendations(data.recommendations);
} catch (error) {
console.error('Error fetching recommendations:', error);
} finally {
setLoading(false);
}
};
</code></pre>
<br>
<h3>4.3 CSS & Styling</h3>
<p><strong>Tailwind CSS<strong>: Utility-first CSS framework</p>
<pre><code class="javascript">
<div className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300">
<h3 className="font-semibold text-gray-800 text-lg mb-1">{product.name}</h3>
<p className="text-sm text-gray-500">{product.category}</p>
</div>
</code></pre>
<br>
<p><strong>Benefits<strong>:</p>
<li>**Rapid development**: Pre-built utility classes</li>
<li>**Consistent design**: Standardized spacing, colors</li>
<li>**Responsive**: Mobile-first approach</li>
<li>**Small bundle size**: Only includes used styles</li>
<br>
<p>---</p>
<br>
<h2>5. Machine Learning Components</h2>
<br>
<h3>5.1 Recommendation Algorithms</h3>
<br>
<h4>5.1.1 Collaborative Filtering</h4>
<p><strong>What it is<strong>: Recommends items based on user behavior patterns.</p>
<br>
<p><strong>How it works<strong>:</p>
<li>**User-Item Matrix**: Create matrix of user interactions</li>
<p>2. <strong>Similarity Calculation<strong>: Find users with similar preferences</p>
<p>3. <strong>Prediction<strong>: Recommend items liked by similar users</p>
<br>
<p><strong>Code Implementation<strong>:</p>
<pre><code class="python">
class CollaborativeFilteringModel:
def __init__(self, n_components=50):
self.model = TruncatedSVD(n_components=n_components, random_state=42)
self.user_item_matrix = None
def train(self, df):
# Create user-item interaction matrix
interaction_matrix = self.prepare_data(df)
# Fit SVD model
self.model.fit(interaction_matrix)
def predict_user_preferences(self, user_id, product_ids):
# Transform user-item matrix
user_features = self.model.transform(self.user_item_matrix)
product_features = self.model.components_.T
# Calculate scores for each product
scores = []
for product_id in product_ids:
score = np.dot(user_vector, product_vector)
scores.append(score)
return scores
</code></pre>
<br>
<h4>5.1.2 Matrix Factorization</h4>
<p><strong>What it is<strong>: Decomposes user-item matrix into user and item factors.</p>
<br>
<p><strong>Mathematical Foundation<strong>:</p>
<pre><code class="">
R ≈ U × V^T
Where:
R = User-Item Rating Matrix (m×n)
U = User Factor Matrix (m×k)
V = Item Factor Matrix (n×k)
k = Number of latent factors
</code></pre>
<br>
<p><strong>Implementation<strong>:</p>
<pre><code class="python">
class MatrixFactorizationModel:
def fit(self, df, epochs=20):
# Initialize factors randomly
self.user_factors = np.random.normal(0, 0.1, (n_users, self.n_factors))
self.item_factors = np.random.normal(0, 0.1, (n_items, self.n_factors))
# SGD training
for epoch in range(epochs):
for user_idx, item_idx, rating in training_data:
# Predict rating
prediction = self.predict_single(user_idx, item_idx)
error = rating - prediction
# Update factors using gradient descent
user_factor = self.user_factors[user_idx].copy()
item_factor = self.item_factors[item_idx].copy()
self.user_factors[user_idx] += learning_rate * (
error * item_factor - regularization * user_factor
)
self.item_factors[item_idx] += learning_rate * (
error * user_factor - regularization * item_factor
)
</code></pre>
<br>
<h3>5.2 Feature Engineering</h3>
<br>
<h4>5.2.1 User Interaction Scoring</h4>
<pre><code class="python">
score_map = {
'view': 1, # Basic interaction
'like': 2, # Positive signal
'cart': 3, # Strong intent
'purchase': 5 # Strongest signal
}
</code></pre>
<br>
<h4>5.2.2 Time Decay</h4>
<pre><code class="python">
def apply_time_decay(score, timestamp, decay_factor=0.1):
"""Apply time decay to interaction scores"""
days_ago = (now - timestamp).days
decayed_score = score * np.exp(-decay_factor * days_ago)
return decayed_score
</code></pre>
<br>
<h3>5.3 Model Ensemble</h3>
<p><strong>Combining multiple algorithms for better performance<strong>:</p>
<br>
<pre><code class="python">
def get_ensemble_recommendations(user_id, num_recommendations=10):
# Get predictions from different models
cf_scores = collaborative_model.predict(user_id, candidate_products)
mf_scores = matrix_factorization_model.predict(user_id, candidate_products)
# Weighted ensemble
ensemble_scores = 0.7 * cf_scores + 0.3 * mf_scores
# Rank and return top recommendations
top_indices = np.argsort(ensemble_scores)[::-1][:num_recommendations]
return [candidate_products[i] for i in top_indices]
</code></pre>
<br>
<p>---</p>
<br>
<h2>6. Database Design</h2>
<br>
<h3>6.1 Entity Relationship Diagram</h3>
<pre><code class="">
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ User │ │ UserBehavior │ │ Product │
│ │ │ │ │ │
│ • id (PK) │◄──►│ • id (PK) │◄──►│ • id (PK) │
│ • username │ │ • user_id (FK) │ │ • name │
│ • email │ │ • product_id(FK)│ │ • description │
│ • password │ │ • interaction │ │ • category │
│ • date_joined │ │ • rating │ │ • price │
└─────────────────┘ │ • timestamp │ │ • created_at │
│ • session_id │ └─────────────────┘
└─────────────────┘
│
▼
┌─────────────────┐
│ UserProfile │
│ │
│ • user_id (FK) │
│ • preferences │
│ • embedding │
│ • last_updated │
└─────────────────┘
</code></pre>
<br>
<h3>6.2 Table Schemas</h3>
<br>
<h4>6.2.1 Products Table</h4>
<pre><code class="sql">
CREATE TABLE products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(200) NOT NULL,
description TEXT,
category VARCHAR(100),
price DECIMAL(10,2),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
</code></pre>
<br>
<h4>6.2.2 User Behavior Table</h4>
<pre><code class="sql">
CREATE TABLE user_behavior (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER REFERENCES auth_user(id),
product_id INTEGER REFERENCES products(id),
interaction_type VARCHAR(20) CHECK (interaction_type IN ('view', 'like', 'cart', 'purchase')),
rating FLOAT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
session_id VARCHAR(100)
);
-- Indexes for performance
CREATE INDEX idx_user_behavior_user ON user_behavior(user_id);
CREATE INDEX idx_user_behavior_product ON user_behavior(product_id);
CREATE INDEX idx_user_behavior_timestamp ON user_behavior(timestamp);
</code></pre>
<br>
<h3>6.3 Data Models in Django</h3>
<br>
<h4>6.3.1 Product Model</h4>
<pre><code class="python">
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
category = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['category']),
models.Index(fields=['price']),
]
def __str__(self):
return self.name
</code></pre>
<br>
<h4>6.3.2 User Behavior Model</h4>
<pre><code class="python">
class UserBehavior(models.Model):
INTERACTION_TYPES = [
('view', 'View'),
('like', 'Like'),
('cart', 'Add to Cart'),
('purchase', 'Purchase'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
interaction_type = models.CharField(max_length=20, choices=INTERACTION_TYPES)
rating = models.FloatField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
session_id = models.CharField(max_length=100, null=True, blank=True)
class Meta:
indexes = [
models.Index(fields=['user', 'product']),
models.Index(fields=['timestamp']),
]
</code></pre>
<br>
<p>---</p>
<br>
<h2>7. API Endpoints</h2>
<br>
<h3>7.1 RESTful API Design Principles</h3>
<br>
<p><strong>REST (Representational State Transfer)<strong> principles:</p>
<li>**Stateless**: Each request contains all necessary information</li>
<li>**Cacheable**: Responses can be cached for performance</li>
<li>**Uniform Interface**: Consistent URL structure</li>
<li>**Resource-Based**: URLs represent resources, not actions</li>
<br>
<h3>7.2 API Endpoint Documentation</h3>
<br>
<h4>7.2.1 Get Recommendations</h4>
<pre><code class="http">
GET /api/recommendations/{user_id}/
</code></pre>
<br>
<p><strong>Parameters<strong>:</p>
<li>`user_id` (int): User ID to get recommendations for</li>
<li>`count` (int, optional): Number of recommendations (default: 10)</li>
<br>
<p><strong>Response<strong>:</p>
<pre><code class="json">
{
"user_id": 1,
"recommendations": [
{
"product_id": 5,
"product_name": "Wireless Headphones",
"category": "Electronics",
"price": 99.99,
"confidence_score": 0.85,
"cf_score": 0.7,
"mf_score": 0.3
}
],
"count": 10
}
</code></pre>
<br>
<p><strong>Implementation<strong>:</p>
<pre><code class="python">
class RecommendationsAPIView(APIView):
def get(self, request, user_id):
try:
count = int(request.query_params.get('count', 10))
# Get recommendations from ML engine
recommendations = recommendation_engine.get_recommendations(
user_id, num_recommendations=count
)
return Response({
'user_id': user_id,
'recommendations': recommendations,
'count': len(recommendations)
}, status=status.HTTP_200_OK)
except Exception as e:
return Response(
{'error': str(e)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
</code></pre>
<br>
<h4>7.2.2 Record User Interaction</h4>
<pre><code class="http">
POST /api/interaction/
</code></pre>
<br>
<p><strong>Request Body<strong>:</p>
<pre><code class="json">
{
"user_id": 1,
"product_id": 5,
"interaction_type": "view",
"rating": 4.5
}
</code></pre>
<br>
<p><strong>Response<strong>:</p>
<pre><code class="json">
{
"message": "Interaction recorded successfully"
}
</code></pre>
<br>
<p><strong>Implementation<strong>:</p>
<pre><code class="python">
class InteractionAPIView(APIView):
def post(self, request):
try:
user_id = request.data.get('user_id')
product_id = request.data.get('product_id')
interaction_type = request.data.get('interaction_type')
rating = request.data.get('rating')
# Validate required fields
if not all([user_id, product_id, interaction_type]):
return Response(
{'error': 'user_id, product_id, and interaction_type are required'},
status=status.HTTP_400_BAD_REQUEST
)
# Record interaction
UserBehavior.objects.create(
user_id=user_id,
product_id=product_id,
interaction_type=interaction_type,
rating=rating
)
# Update recommendations asynchronously
recommendation_engine.record_interaction(user_id, product_id, interaction_type)
return Response(
{'message': 'Interaction recorded successfully'},
status=status.HTTP_201_CREATED
)
except Exception as e:
return Response(
{'error': str(e)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
</code></pre>
<br>
<h4>7.2.3 Search Products</h4>
<pre><code class="http">
GET /api/search/?q=electronics&user_id=1
</code></pre>
<br>
<p><strong>Parameters<strong>:</p>
<li>`q` (string): Search query</li>
<li>`user_id` (int, optional): User ID for personalization</li>
<br>
<p><strong>Response<strong>:</p>
<pre><code class="json">
{
"products": [
{
"id": 1,
"name": "Smartphone Pro",
"category": "Electronics",
"price": 699.99,
"description": "Latest smartphone...",
"personalization_score": 0.75
}
],
"count": 1
}
</code></pre>
<br>
<h3>7.3 HTTP Status Codes</h3>
<br>
<tr><td>Code</td><td>Meaning</td><td>When to Use</td></tr>
<tr><td>200</td><td>OK</td><td>Successful GET request</td></tr>
<tr><td>201</td><td>Created</td><td>Successful POST request (resource created)</td></tr>
<tr><td>400</td><td>Bad Request</td><td>Invalid request data</td></tr>
<tr><td>404</td><td>Not Found</td><td>Resource doesn't exist</td></tr>
<tr><td>405</td><td>Method Not Allowed</td><td>Wrong HTTP method</td></tr>
<tr><td>500</td><td>Internal Server Error</td><td>Server-side error</td></tr>
<br>
<h3>7.4 Error Handling</h3>
<pre><code class="python">
def handle_api_error(view_func):
"""Decorator for consistent error handling"""
def wrapper(*args, **kwargs):
try:
return view_func(*args, **kwargs)
except ValidationError as e:
return Response(
{'error': 'Validation failed', 'details': str(e)},
status=status.HTTP_400_BAD_REQUEST
)
except ObjectDoesNotExist as e:
return Response(
{'error': 'Resource not found', 'details': str(e)},
status=status.HTTP_404_NOT_FOUND
)
except Exception as e:
logger.error(f"Unexpected error in {view_func.__name__}: {str(e)}")
return Response(
{'error': 'Internal server error'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
return wrapper
</code></pre>
<br>
<p>---</p>
<br>
<h2>8. Deployment & DevOps</h2>
<br>
<h3>8.1 Docker Containerization</h3>
<br>
<h4>8.1.1 Backend Dockerfile</h4>
<pre><code class="dockerfile">
FROM python:3.10-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Expose port
EXPOSE 8000
# Run application
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code></pre>
<br>
<h4>8.1.2 Frontend Dockerfile</h4>
<pre><code class="dockerfile">
FROM node:18-alpine
WORKDIR /app
# Install dependencies
COPY package*.json ./
RUN npm install
# Copy source code
COPY . .
# Build application
RUN npm run build
# Serve with nginx
FROM nginx:alpine
COPY --from=0 /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code></pre>
<br>
<h3>8.2 Docker Compose</h3>
<p><strong>Purpose<strong>: Orchestrate multiple containers together</p>
<br>
<pre><code class="yaml">
version: '3.8'
services:
# PostgreSQL Database
postgres:
image: postgres:13
environment:
POSTGRES_DB: ecommerce_rec
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
# Redis Cache
redis:
image: redis:alpine
ports:
- "6379:6379"
# Django Backend
backend:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- postgres
- redis
environment:
- DATABASE_URL=postgresql://postgres:password@postgres:5432/ecommerce_rec
- REDIS_URL=redis://redis:6379/0
# React Frontend
frontend:
build: ./frontend
ports:
- "3000:3000"
depends_on:
- backend
environment:
- REACT_APP_API_URL=http://localhost:8000/api
volumes:
postgres_data:
</code></pre>
<br>
<h3>8.3 Environment Configuration</h3>
<br>
<h4>8.3.1 Development Settings (`settings_dev.py`)</h4>
<pre><code class="python">
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Simplified cache for development
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
</code></pre>
<br>
<h4>8.3.2 Production Settings (`settings_prod.py`)</h4>
<pre><code class="python">
DEBUG = False
ALLOWED_HOSTS = ['your-domain.com', 'api.your-domain.com']