File size: 4,527 Bytes
99bbd64
d034937
99bbd64
89ac774
d034937
 
 
 
 
 
7dbf682
41d24fb
 
7dbf682
41d24fb
afbea99
41d24fb
 
 
bcc36a0
24a440f
fa24c7d
925e026
 
a69d06f
925e026
41d24fb
 
 
 
 
 
 
 
 
 
 
 
d034937
41d24fb
 
 
 
 
d034937
41d24fb
 
 
 
 
d034937
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41d24fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#Fast APi Packages
from fastapi import FastAPI,File, HTTPException
from pydantic import BaseModel
import json
from typing import List, Dict, Any
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse
from datetime import datetime
import warnings
import os
import logging

warnings.filterwarnings('ignore')

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# Get the current directory path
current_dir = os.path.dirname(os.path.abspath(__file__))
excel_path = os.path.join(current_dir, 'DataSetSample.xlsx')

# Log the file path and directory contents for debugging
logger.info(f"Current directory: {current_dir}")
logger.info(f"Excel path: {excel_path}")
logger.info("Directory contents:")
for file in os.listdir(current_dir):
    logger.info(f"- {file}")

try:
    # Load the data when the application starts
    purchase_history = pd.read_excel(excel_path, sheet_name='Transaction History', 
                                   parse_dates=['Purchase_Date'])
    logger.info("Successfully loaded Excel file")
    
    purchase_history['Customer_Id'] = purchase_history['Customer_Id'].astype(str)
    product_categories = purchase_history[['Product_Id', 'Category']].drop_duplicates().set_index('Product_Id')['Category'].to_dict()
    purchase_counts = purchase_history.groupby(['Customer_Id', 'Product_Id']).size().unstack(fill_value=0)
    sparse_purchase_counts = sparse.csr_matrix(purchase_counts)
    cosine_similarities = cosine_similarity(sparse_purchase_counts.T)
    
    logger.info("Data processing completed successfully")
    
except Exception as e:
    logger.error(f"Error loading or processing data: {str(e)}")
    raise

def get_customer_items_and_recommendations(user_id: str, n: int = 5) -> tuple[List[Dict], List[Dict]]:
    """
    Get both purchased items and recommendations for a user
    """
    user_id = str(user_id)
    
    if user_id not in purchase_counts.index:
        return [], []
    
    purchased_items = list(purchase_counts.columns[purchase_counts.loc[user_id] > 0])
    
    purchased_items_info = []
    user_purchases = purchase_history[purchase_history['Customer_Id'] == user_id]
    
    for item in purchased_items:
        item_purchases = user_purchases[user_purchases['Product_Id'] == item]
        total_amount = float(item_purchases['Amount (In Dollars)'].sum())
        last_purchase = pd.to_datetime(item_purchases['Purchase_Date'].max())
        category = product_categories.get(item, 'Unknown')
        purchased_items_info.append({
            'product_id': item,
            'category': category,
            'total_amount': total_amount,
            'last_purchase': last_purchase.strftime('%Y-%m-%d')
        })
    
    user_idx = purchase_counts.index.get_loc(user_id)
    user_history = sparse_purchase_counts[user_idx].toarray().flatten()
    similarities = cosine_similarities.dot(user_history)
    purchased_indices = np.where(user_history > 0)[0]
    similarities[purchased_indices] = 0
    recommended_indices = np.argsort(similarities)[::-1][:n]
    recommended_items = list(purchase_counts.columns[recommended_indices])
    recommended_items = [item for item in recommended_items if item not in purchased_items]
    
    recommended_items_info = [
        {
            'product_id': item,
            'category': product_categories.get(item, 'Unknown')
        }
        for item in recommended_items
    ]

    return purchased_items_info, recommended_items_info

@app.get("/")
async def root():
    return {"message": "Welcome to the Recommendation API"}

@app.get("/recommendations/{customer_id}")
async def get_recommendations(customer_id: str, n: int = 5):
    """
    Get recommendations for a customer
    
    Parameters:
    - customer_id: The ID of the customer
    - n: Number of recommendations to return (default: 5)
    
    Returns:
    - JSON object containing purchase history and recommendations
    """
    try:
        purchased_items, recommended_items = get_customer_items_and_recommendations(customer_id, n)
        
        return {
            "customer_id": customer_id,
            "purchase_history": purchased_items,
            "recommendations": recommended_items
        }
    except Exception as e:
        logger.error(f"Error processing request for customer {customer_id}: {str(e)}")
        raise HTTPException(status_code=404, detail=f"Error processing customer ID: {customer_id}. {str(e)}")