Vaibhav84 commited on
Commit
7a69cc2
·
1 Parent(s): 3d9c6c2
Files changed (1) hide show
  1. app.py +147 -1
app.py CHANGED
@@ -14,7 +14,8 @@ import os
14
  import logging
15
  import requests
16
  import io
17
-
 
18
 
19
  warnings.filterwarnings('ignore')
20
 
@@ -37,6 +38,11 @@ try:
37
  excel_content = io.BytesIO(response.content)
38
  purchase_history = pd.read_excel(excel_content, sheet_name='Transaction History',
39
  parse_dates=['Purchase_Date'])
 
 
 
 
 
40
  logger.info("Successfully downloaded and loaded Excel file")
41
 
42
  # Process the data
@@ -45,6 +51,14 @@ try:
45
  purchase_counts = purchase_history.groupby(['Customer_Id', 'Product_Id']).size().unstack(fill_value=0)
46
  sparse_purchase_counts = sparse.csr_matrix(purchase_counts)
47
  cosine_similarities = cosine_similarity(sparse_purchase_counts.T)
 
 
 
 
 
 
 
 
48
 
49
  logger.info("Data processing completed successfully")
50
 
@@ -208,3 +222,135 @@ async def login(customer_id: str, password: str):
208
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
209
  detail=f"Error during login process: {str(e)}"
210
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  import logging
15
  import requests
16
  import io
17
+ from sklearn.preprocessing import StandardScaler
18
+ from collections import defaultdict
19
 
20
  warnings.filterwarnings('ignore')
21
 
 
38
  excel_content = io.BytesIO(response.content)
39
  purchase_history = pd.read_excel(excel_content, sheet_name='Transaction History',
40
  parse_dates=['Purchase_Date'])
41
+
42
+ # Read Customer Profile sheet
43
+ excel_content.seek(0) # Reset buffer position
44
+ customer_profiles = pd.read_excel(excel_content, sheet_name='Customer Profile (Individual)')
45
+
46
  logger.info("Successfully downloaded and loaded Excel file")
47
 
48
  # Process the data
 
51
  purchase_counts = purchase_history.groupby(['Customer_Id', 'Product_Id']).size().unstack(fill_value=0)
52
  sparse_purchase_counts = sparse.csr_matrix(purchase_counts)
53
  cosine_similarities = cosine_similarity(sparse_purchase_counts.T)
54
+
55
+ # Process customer profiles data
56
+ customer_profiles['Customer_Id'] = customer_profiles['Customer_Id'].astype(str)
57
+
58
+ # Normalize numerical features if they exist
59
+ numerical_features = ['Age', 'Income'] # Add or modify based on your actual columns
60
+ scaler = StandardScaler()
61
+ customer_profiles[numerical_features] = scaler.fit_transform(customer_profiles[numerical_features])
62
 
63
  logger.info("Data processing completed successfully")
64
 
 
222
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
223
  detail=f"Error during login process: {str(e)}"
224
  )
225
+ # Add content recommendation function
226
+ def get_content_recommendations(customer_id: str, n: int = 5) -> List[Dict]:
227
+ """
228
+ Get content recommendations based on customer profile
229
+ """
230
+ try:
231
+ # Get customer profile
232
+ customer_profile = customer_profiles[customer_profiles['Customer_Id'] == customer_id].iloc[0]
233
+
234
+ # Define content rules based on customer attributes
235
+ content_suggestions = []
236
+
237
+ # Age-based recommendations
238
+ age = customer_profile['Age'] * scaler.scale_[0] + scaler.mean_[0] # Denormalize age
239
+
240
+ if age < 25:
241
+ content_suggestions.extend([
242
+ {"type": "Video", "title": "Getting Started with Personal Finance", "category": "Financial Education"},
243
+ {"type": "Article", "title": "Budgeting Basics for Young Adults", "category": "Financial Planning"},
244
+ {"type": "Interactive", "title": "Investment 101 Quiz", "category": "Education"}
245
+ ])
246
+ elif age < 40:
247
+ content_suggestions.extend([
248
+ {"type": "Video", "title": "Investment Strategies for Growing Wealth", "category": "Investment"},
249
+ {"type": "Article", "title": "Family Financial Planning Guide", "category": "Financial Planning"},
250
+ {"type": "Webinar", "title": "Real Estate Investment Basics", "category": "Investment"}
251
+ ])
252
+ else:
253
+ content_suggestions.extend([
254
+ {"type": "Video", "title": "Retirement Planning Strategies", "category": "Retirement"},
255
+ {"type": "Article", "title": "Estate Planning Essentials", "category": "Financial Planning"},
256
+ {"type": "Webinar", "title": "Tax Optimization for Retirement", "category": "Tax Planning"}
257
+ ])
258
+
259
+ # Income-based recommendations
260
+ income = customer_profile['Income'] * scaler.scale_[1] + scaler.mean_[1] # Denormalize income
261
+
262
+ if income < 50000:
263
+ content_suggestions.extend([
264
+ {"type": "Video", "title": "Debt Management Strategies", "category": "Debt Management"},
265
+ {"type": "Article", "title": "Saving on a Tight Budget", "category": "Budgeting"}
266
+ ])
267
+ elif income < 100000:
268
+ content_suggestions.extend([
269
+ {"type": "Video", "title": "Tax-Efficient Investment Strategies", "category": "Investment"},
270
+ {"type": "Article", "title": "Maximizing Your 401(k)", "category": "Retirement"}
271
+ ])
272
+ else:
273
+ content_suggestions.extend([
274
+ {"type": "Video", "title": "Advanced Tax Planning Strategies", "category": "Tax Planning"},
275
+ {"type": "Article", "title": "High-Net-Worth Investment Guide", "category": "Investment"}
276
+ ])
277
+
278
+ # Add personalization based on purchase history
279
+ if customer_id in purchase_history['Customer_Id'].unique():
280
+ customer_purchases = purchase_history[purchase_history['Customer_Id'] == customer_id]
281
+ categories = customer_purchases['Category'].unique()
282
+
283
+ for category in categories:
284
+ if category == 'Investment':
285
+ content_suggestions.append({
286
+ "type": "Video",
287
+ "title": f"Advanced {category} Strategies",
288
+ "category": category
289
+ })
290
+ elif category == 'Insurance':
291
+ content_suggestions.append({
292
+ "type": "Article",
293
+ "title": f"Understanding Your {category} Options",
294
+ "category": category
295
+ })
296
+
297
+ # Remove duplicates and limit to n recommendations
298
+ seen = set()
299
+ unique_suggestions = []
300
+ for suggestion in content_suggestions:
301
+ key = (suggestion['title'], suggestion['type'])
302
+ if key not in seen:
303
+ seen.add(key)
304
+ unique_suggestions.append(suggestion)
305
+
306
+ return unique_suggestions[:n]
307
+
308
+ except Exception as e:
309
+ logger.error(f"Error generating content recommendations: {str(e)}")
310
+ return []
311
+
312
+ # Add new endpoint for content recommendations
313
+ @app.get("/content-recommendations/{customer_id}")
314
+ async def get_customer_content_recommendations(customer_id: str, n: int = 5):
315
+ """
316
+ Get personalized content recommendations for a customer
317
+
318
+ Parameters:
319
+ - customer_id: The ID of the customer
320
+ - n: Number of recommendations to return (default: 5)
321
+
322
+ Returns:
323
+ - JSON object containing personalized content recommendations
324
+ """
325
+ try:
326
+ # Validate customer
327
+ if customer_id not in customer_profiles['Customer_Id'].unique():
328
+ raise HTTPException(
329
+ status_code=status.HTTP_404_NOT_FOUND,
330
+ detail="Customer ID not found"
331
+ )
332
+
333
+ # Get customer profile summary
334
+ customer_profile = customer_profiles[customer_profiles['Customer_Id'] == customer_id].iloc[0]
335
+ profile_summary = {
336
+ "age_group": "Young" if customer_profile['Age'] < 25 else "Middle" if customer_profile['Age'] < 40 else "Senior",
337
+ "income_level": "Low" if customer_profile['Income'] < 50000 else "Medium" if customer_profile['Income'] < 100000 else "High"
338
+ }
339
+
340
+ # Get content recommendations
341
+ recommendations = get_content_recommendations(customer_id, n)
342
+
343
+ return {
344
+ "customer_id": customer_id,
345
+ "profile_summary": profile_summary,
346
+ "recommendations": recommendations
347
+ }
348
+
349
+ except HTTPException:
350
+ raise
351
+ except Exception as e:
352
+ logger.error(f"Error processing content recommendations for customer {customer_id}: {str(e)}")
353
+ raise HTTPException(
354
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
355
+ detail=f"Error processing request: {str(e)}"
356
+ )