Spaces:
Sleeping
Sleeping
API
Browse files
app.py
CHANGED
@@ -11,6 +11,7 @@ from datetime import datetime
|
|
11 |
import warnings
|
12 |
import os
|
13 |
import logging
|
|
|
14 |
|
15 |
warnings.filterwarnings('ignore')
|
16 |
|
@@ -20,23 +21,44 @@ logger = logging.getLogger(__name__)
|
|
20 |
|
21 |
app = FastAPI()
|
22 |
|
23 |
-
#
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
|
|
28 |
logger.info(f"Current directory: {current_dir}")
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
try:
|
35 |
-
#
|
36 |
-
purchase_history = pd.read_excel(excel_path, sheet_name='Transaction History',
|
37 |
-
parse_dates=['Purchase_Date'])
|
38 |
-
logger.info("Successfully loaded Excel file")
|
39 |
-
|
40 |
purchase_history['Customer_Id'] = purchase_history['Customer_Id'].astype(str)
|
41 |
product_categories = purchase_history[['Product_Id', 'Category']].drop_duplicates().set_index('Product_Id')['Category'].to_dict()
|
42 |
purchase_counts = purchase_history.groupby(['Customer_Id', 'Product_Id']).size().unstack(fill_value=0)
|
@@ -46,7 +68,7 @@ try:
|
|
46 |
logger.info("Data processing completed successfully")
|
47 |
|
48 |
except Exception as e:
|
49 |
-
logger.error(f"Error
|
50 |
raise
|
51 |
|
52 |
def get_customer_items_and_recommendations(user_id: str, n: int = 5) -> tuple[List[Dict], List[Dict]]:
|
@@ -96,7 +118,11 @@ def get_customer_items_and_recommendations(user_id: str, n: int = 5) -> tuple[Li
|
|
96 |
|
97 |
@app.get("/")
|
98 |
async def root():
|
99 |
-
return {
|
|
|
|
|
|
|
|
|
100 |
|
101 |
@app.get("/recommendations/{customer_id}")
|
102 |
async def get_recommendations(customer_id: str, n: int = 5):
|
@@ -121,3 +147,25 @@ async def get_recommendations(customer_id: str, n: int = 5):
|
|
121 |
except Exception as e:
|
122 |
logger.error(f"Error processing request for customer {customer_id}: {str(e)}")
|
123 |
raise HTTPException(status_code=404, detail=f"Error processing customer ID: {customer_id}. {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
import warnings
|
12 |
import os
|
13 |
import logging
|
14 |
+
import pathlib
|
15 |
|
16 |
warnings.filterwarnings('ignore')
|
17 |
|
|
|
21 |
|
22 |
app = FastAPI()
|
23 |
|
24 |
+
# Try multiple possible paths for the Excel file
|
25 |
+
possible_paths = [
|
26 |
+
'datasetsample.xlsx', # Same directory
|
27 |
+
'./datasetsample.xlsx', # Explicit current directory
|
28 |
+
'../datasetsample.xlsx', # Parent directory
|
29 |
+
'/home/user/app/datasetsample.xlsx', # Hugging Face default path
|
30 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'datasetsample.xlsx'), # Absolute path
|
31 |
+
]
|
32 |
|
33 |
+
logger.info("Checking directory contents:")
|
34 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
35 |
logger.info(f"Current directory: {current_dir}")
|
36 |
+
try:
|
37 |
+
for item in os.listdir(current_dir):
|
38 |
+
logger.info(f"Found file: {item}")
|
39 |
+
except Exception as e:
|
40 |
+
logger.error(f"Error listing directory: {str(e)}")
|
41 |
+
|
42 |
+
# Try each possible path
|
43 |
+
purchase_history = None
|
44 |
+
for path in possible_paths:
|
45 |
+
try:
|
46 |
+
logger.info(f"Attempting to load Excel file from: {path}")
|
47 |
+
purchase_history = pd.read_excel(path, sheet_name='Transaction History',
|
48 |
+
parse_dates=['Purchase_Date'])
|
49 |
+
logger.info(f"Successfully loaded Excel file from: {path}")
|
50 |
+
break
|
51 |
+
except Exception as e:
|
52 |
+
logger.warning(f"Failed to load from {path}: {str(e)}")
|
53 |
+
continue
|
54 |
+
|
55 |
+
if purchase_history is None:
|
56 |
+
error_msg = "Failed to load Excel file from any location"
|
57 |
+
logger.error(error_msg)
|
58 |
+
raise FileNotFoundError(error_msg)
|
59 |
|
60 |
try:
|
61 |
+
# Process the data
|
|
|
|
|
|
|
|
|
62 |
purchase_history['Customer_Id'] = purchase_history['Customer_Id'].astype(str)
|
63 |
product_categories = purchase_history[['Product_Id', 'Category']].drop_duplicates().set_index('Product_Id')['Category'].to_dict()
|
64 |
purchase_counts = purchase_history.groupby(['Customer_Id', 'Product_Id']).size().unstack(fill_value=0)
|
|
|
68 |
logger.info("Data processing completed successfully")
|
69 |
|
70 |
except Exception as e:
|
71 |
+
logger.error(f"Error processing data: {str(e)}")
|
72 |
raise
|
73 |
|
74 |
def get_customer_items_and_recommendations(user_id: str, n: int = 5) -> tuple[List[Dict], List[Dict]]:
|
|
|
118 |
|
119 |
@app.get("/")
|
120 |
async def root():
|
121 |
+
return {
|
122 |
+
"message": "Welcome to the Recommendation API",
|
123 |
+
"status": "running",
|
124 |
+
"data_loaded": purchase_history is not None
|
125 |
+
}
|
126 |
|
127 |
@app.get("/recommendations/{customer_id}")
|
128 |
async def get_recommendations(customer_id: str, n: int = 5):
|
|
|
147 |
except Exception as e:
|
148 |
logger.error(f"Error processing request for customer {customer_id}: {str(e)}")
|
149 |
raise HTTPException(status_code=404, detail=f"Error processing customer ID: {customer_id}. {str(e)}")
|
150 |
+
|
151 |
+
# Add a health check endpoint that includes file system information
|
152 |
+
@app.get("/health")
|
153 |
+
async def health_check():
|
154 |
+
"""
|
155 |
+
Health check endpoint that returns system information
|
156 |
+
"""
|
157 |
+
try:
|
158 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
159 |
+
files = os.listdir(current_dir)
|
160 |
+
|
161 |
+
return {
|
162 |
+
"status": "healthy",
|
163 |
+
"current_directory": current_dir,
|
164 |
+
"files_found": files,
|
165 |
+
"data_loaded": purchase_history is not None
|
166 |
+
}
|
167 |
+
except Exception as e:
|
168 |
+
return {
|
169 |
+
"status": "unhealthy",
|
170 |
+
"error": str(e)
|
171 |
+
}
|