Spaces:
Runtime error
Runtime error
File size: 16,801 Bytes
569c655 e1c6a58 569c655 e1c6a58 569c655 fdced54 569c655 e1c6a58 569c655 2aa6d5a 631e806 2aa6d5a 8ebe6ba fbb9bcf 01fb678 569c655 fbb9bcf 4441bb9 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 2107dea fbb9bcf 4441bb9 37095c4 0d04590 37095c4 35f32fc 74c73a7 3e5ce2e bfe8a5b 569c655 3e5ce2e 569c655 64a928c 569c655 64a928c 7762e93 64a928c 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf fdced54 fbb9bcf fdced54 fbb9bcf fdced54 fbb9bcf fdced54 569c655 fdced54 fbb9bcf fdced54 fbb9bcf fdced54 fbb9bcf fdced54 fbb9bcf fdced54 fbb9bcf 569c655 27fa4d4 cf43d11 b1235b7 84178af b1235b7 569c655 27fa4d4 b1235b7 27fa4d4 b1235b7 27fa4d4 c97c249 b1235b7 47c282a cf43d11 b1235b7 04b7f67 b1235b7 47c282a f00497a b1235b7 f00497a b1235b7 f00497a b1235b7 f00497a c80a2f9 b1235b7 cf43d11 b1235b7 569c655 fbb9bcf fdced54 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 fbb9bcf 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 569c655 9f4d232 bbd289f 9f4d232 41afb82 fcc39f7 569c655 9f4d232 569c655 9f4d232 7733e8f 0800c74 9bb8df6 7733e8f fdced54 fb65e83 7733e8f |
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 |
from fastapi import FastAPI, HTTPException, Form, Request
from fastapi.responses import JSONResponse
import torch
import pandas as pd
import logging
import torch.nn as nn
from sklearn.preprocessing import MinMaxScaler
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import degree
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn import preprocessing as pp
import json
from pydantic import BaseModel
from typing import List, Optional
import gradio as gr
import os
from datasets import load_dataset
from scheduler import get_latest_model
cache_base = "/app/cache"
os.makedirs(f"{cache_base}/huggingface", exist_ok=True)
os.makedirs(f"{cache_base}/transformers", exist_ok=True)
os.makedirs(f"{cache_base}/datasets", exist_ok=True)
# Set all possible Hugging Face cache environment variables
os.environ['HF_HOME'] = f"{cache_base}/huggingface"
os.environ['TRANSFORMERS_CACHE'] = f"{cache_base}/transformers"
os.environ['HF_DATASETS_CACHE'] = f"{cache_base}/datasets"
os.environ['HUGGINGFACE_HUB_CACHE'] = f"{cache_base}/huggingface"
os.environ['HF_HUB_CACHE'] = f"{cache_base}/huggingface"
# Initialize FastAPI and logging
app = FastAPI()
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
product_gender_mapping = {
"Dental Care Kits": "Unisex",
"Lamb Meat": "Unisex",
"Whole Chicken": "Unisex",
"Hyaluronic Acid": "Female",
"Whitening Toothpaste": "Unisex",
"Pure Sesame Oil": "Unisex",
"Modern Literature": "Unisex",
"Organic Sesame Oil": "Unisex",
"Premium Olive Oil": "Unisex",
"Historical Fiction": "Unisex",
"Home Decorations": "Unisex",
"Minced Meat": "Unisex",
"Fresh Milk": "Unisex",
"Skin Health Products": "Female",
"Kitchen Towels": "Unisex",
"Mineral Water": "Unisex",
"Frozen Chicken Drumsticks": "Unisex",
"Premium Bedding": "Unisex",
"Pepsi Soft Drink": "Unisex",
"Organic Milk": "Unisex",
"Refined Olive Oil": "Unisex",
"Tomato Paste": "Unisex",
"Burger Sauce": "Unisex",
"Xbox Series X": "Male",
"Smart LED TV": "Unisex",
"MacBook Pro 16-inch": "Unisex",
"iPhone15": "Unisex",
"Innovative Home Appliances": "Unisex",
"Windbreaker Jacket": "Male",
"Natural Shampoo": "Female",
"Classic Fiction": "Unisex",
"Eyeliner": "Female",
"Creamy Mayonnaise": "Unisex",
"Coca-Cola Soft Drink": "Unisex",
"Training Shorts": "Male",
"Pavilion Laptop": "Unisex",
"Hyaluronic Acid": "Female",
"Inspiron Laptop": "Unisex",
"Snack Bars": "Unisex",
"Tomato Ketchup": "Unisex",
"Blender": "Unisex",
"Energy-Efficient Air Conditioner": "Unisex",
"Conditionar": "Female",
"Advanced Washing Machine": "Unisex",
"Hand Cream": "Female",
"Hair Cream": "Female",
"Mascara": "Female",
"Bluetooth Audio System": "Unisex",
"Sports Shoes": "Unisex",
"PlayStation Console": "Male",
"Chili Sauce": "Unisex",
"Smart Refrigerator": "Unisex",
"Bravia Television": "Unisex",
"Formal Shirt": "Male",
"ThinkPad Laptop": "Unisex",
"Blended Sunflower Oil": "Unisex",
"iPhone14": "Unisex",
"Split Air Conditioner": "Unisex",
"MacBook Pro 13-inch": "Unisex",
"Athletic T-shirt": "Male",
"iPad": "Unisex",
"Galaxy Tablet": "Unisex",
"Popular Non-Fiction": "Unisex",
"High-Capacity Washing Machine": "Unisex",
"iPhone13": "Unisex",
"Hair Repair Shampoo": "Female",
"Microwave Oven": "Unisex",
"Eyeliner": "Female",
"Consumer Electronics": "Unisex",
"Durable Home Appliances": "Unisex",
"Multi-Function Home Appliances": "Unisex",
"Hydrating Skincare": "Female",
"MacBook Air": "Unisex",
"Fruit Juice": "Unisex",
"Healthy Juice": "Unisex",
"Evening Dress": "Female",
"Body Care Essentials": "Female",
"Mascara": "Female",
"Frozen Chicken": "Unisex",
"Hair Serum": "Female",
"Ground Meat": "Unisex",
"Eyeliner": "Female",
"Workout T-shirt": "Male",
"Living Room Furniture": "Unisex",
"Milk Chocolate": "Unisex",
"Shampoo": "Female",
"Frozen Chicken Wings": "Unisex",
"Beef Cuts": "Unisex",
"Instant Coffee": "Unisex",
"Home Decorations": "Unisex",
"Power Tools": "Male",
"Coffee Maker": "Unisex",
"Modular Furniture": "Unisex",
"Smart TV": "Unisex",
"Sunflower Cooking Oil": "Unisex",
"Running Shoes": "Unisex",
"Gentle Body Care": "Female",
"Mascara": "Female",
"Bathroom Accessories": "Unisex",
"Hair Cream": "Female",
"Comfort Bedding": "Unisex",
"Thriller Novel": "Unisex",
"Track Jacket": "Male",
"MacBook Pro 14-inch": "Unisex",
"LED Lighting": "Unisex",
"Galaxy Smartphone": "Unisex",
"Contemporary Literature": "Unisex",
"Bathroom Essentials": "Unisex",
"Natural Juice": "Unisex",
"Smart Watch": "Unisex",
"Conditionar": "Female",
"Shampoo": "Female",
"Casual Jacket": "Male",
"iPhone16": "Unisex",
"iPhone11": "Unisex",
}
# Set device to GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# # Load and preprocess data
# df_all = pd.read_csv("transactions.csv")
# Set a writable cache directory
os.environ["HF_HOME"] = "/tmp/hf_cache" # Use /tmp, which is writable in Spaces
os.makedirs(os.environ["HF_HOME"], exist_ok=True)
user_encoder = pp.LabelEncoder()
item_encoder = pp.LabelEncoder()
# Load dataset with custom cache directory
dataset_all = load_dataset("FarahMohsenSamy1/Transactions", cache_dir=os.environ["HF_HOME"])
df = dataset_all['train'].to_pandas() # Convert to pandas DataFrame
df["user_id_idx"] = user_encoder.fit_transform(df["Customer_ID"])
user_encoder = pp.LabelEncoder()
item_encoder = pp.LabelEncoder()
df["user_id_idx"] = user_encoder.fit_transform(df["Customer_ID"])
df["item_id_idx"] = item_encoder.fit_transform(df["Item_ID"])
# df['Timestamp'] = pd.to_datetime(df['Timestamp'])
# df['Timestamp_numeric'] = df['Timestamp'].astype('int64') // 10**9 # Seconds since epoch
# df["scaled_timestamp"] = MinMaxScaler().fit_transform(df[["Timestamp_numeric"]])
latent_dim = 64
n_layers = 3
n_users = df["user_id_idx"].nunique()
n_items = df["item_id_idx"].nunique()
COLLAB_WEIGHT = 0.5
CONTENT_WEIGHT = 0.5
# Label encoding and scaling
user_label_encoder = pp.LabelEncoder()
item_label_encoder = pp.LabelEncoder()
date_scaler = MinMaxScaler()
def preprocess_data(df, le_user=None, le_item=None, scaler=None):
if le_user is not None:
df["user_id_idx"] = le_user.fit_transform(df["Customer_ID"].values)
if le_item is not None:
df["item_id_idx"] = le_item.fit_transform(df["Item_ID"].values)
df["Timestamp"] = pd.to_datetime(df["Timestamp"], unit='s')
if scaler is not None:
# Option 1: scale based on numeric timestamp
df["Timestamp_numeric"] = df["Timestamp"].astype(np.int64) // 10**9
df["Date"] = scaler.fit_transform(df[["Timestamp_numeric"]])
return df
preprocessed_df = preprocess_data(
df, user_label_encoder, item_label_encoder, date_scaler
)
# Prepare edge_index for the graph-based model
u_t = torch.LongTensor(preprocessed_df.user_id_idx.values)
i_t = torch.LongTensor(preprocessed_df.item_id_idx.values) + n_users
edge_index = torch.stack((torch.cat([u_t, i_t]), torch.cat([i_t, u_t]))).to(device)
# Define LightGCNConv model
class LightGCNConv(MessagePassing):
def __init__(self, **kwargs):
super().__init__(aggr="add")
def forward(self, x, edge_index):
from_, to_ = edge_index
deg = degree(to_, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt == float("inf")] = 0
norm = deg_inv_sqrt[from_] * deg_inv_sqrt[to_]
return self.propagate(edge_index, x=x, norm=norm)
def message(self, x_j, norm):
return norm.view(-1, 1) * x_j
class RecSysGNN(nn.Module):
def __init__(self, latent_dim, num_layers, num_users, num_items):
super(RecSysGNN, self).__init__()
self.embedding = nn.Embedding(num_users + num_items, latent_dim)
self.convs = nn.ModuleList(LightGCNConv() for _ in range(num_layers))
self.init_parameters()
def init_parameters(self):
nn.init.normal_(self.embedding.weight, std=0.1)
def forward(self, edge_index):
emb0 = self.embedding.weight
embs = [emb0]
emb = emb0
for conv in self.convs:
emb = conv(x=emb, edge_index=edge_index)
embs.append(emb)
out = torch.mean(torch.stack(embs, dim=0), dim=0)
return emb0, out
# model_path = get_latest_model()
MODEL_PATH_FILE = "/app/models/latest_model.txt"
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def get_model_path():
"""Reads the latest model path from the file."""
if os.path.exists(MODEL_PATH_FILE):
with open(MODEL_PATH_FILE, "r") as f:
return f.read().strip()
return None
# Retrieve the model path from the file
model_path = get_model_path()
if not model_path:
raise FileNotFoundError("Model path file is missing or empty. Please train the model first.")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model file not found at '{model_path}'. Please train the model first.")
print(f" Loading model from: {model_path}")
# Initialize the model
model = RecSysGNN(
latent_dim=64, num_layers=3, num_users=n_users, num_items=n_items
).to(device)
# Load the state dictionary
state_dict = torch.load(model_path, map_location=device)
model_state = model.state_dict()
# Filter the state_dict to only load matching parameters
filtered_state_dict = {k: v for k, v in state_dict.items() if k in model_state and v.size() == model_state[k].size()}
# Update the model state dictionary with the filtered parameters
model_state.update(filtered_state_dict)
# Load the model state into the model
model.load_state_dict(model_state)
# Set the model to evaluation mode
model.eval()
print(f" Model loaded successfully from: {model_path}")
# Create user-product rating matrix
user_product_rating = preprocessed_df.pivot_table(
index="user_id_idx", columns="Item_ID", values="rating"
)
user_product_rating.fillna(0, inplace=True)
# Cosine similarity for content-based filtering
product_features = (
preprocessed_df[["Item_ID", "Product_Name", "Product_Category", "Product_Brand", "Price"]]
.drop_duplicates()
.set_index("Item_ID")
)
product_features_encoded = pd.get_dummies(product_features)
cosine_sim_df = pd.DataFrame(
cosine_similarity(product_features_encoded),
index=product_features_encoded.index,
columns=product_features_encoded.index,
)
# Item ID mapping
item_id_mapping = dict(zip(preprocessed_df["item_id_idx"], preprocessed_df["Item_ID"]))
product_name_mapping = dict(
zip(preprocessed_df["Item_ID"], preprocessed_df["Product_Name"])
)
user_gender_mapping = dict(
zip(preprocessed_df["user_id_idx"], preprocessed_df["Customer_Gender"])
)
cosine_sim_df.fillna(0, inplace=True)
# Set up logging configuration
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
def content_based_filtering(user_id, top_k=20, time_weight=0.5):
try:
logging.info(f"Started content-based filtering for user {user_id}")
user_transactions = df[df["user_id_idx"] == user_id].sort_values(by="Timestamp", ascending=False)
content_scores = []
if user_id not in user_product_rating.index:
logging.warning(f"User {user_id} not found in rating matrix.")
return []
user_ratings = user_product_rating.loc[user_id]
for _, transaction in user_transactions.iterrows():
product = transaction["Item_ID"]
timestamp = transaction["Timestamp"]
time_factor = 1 / (1 + np.exp(-time_weight * timestamp))
if product in cosine_sim_df.index:
similar_products = cosine_sim_df.loc[product].nlargest(top_k)
for similar_product, score in similar_products.items():
weighted_score = (score * user_ratings.get(product, 0)) * time_factor
content_scores.append({
"item_id": similar_product,
"score": weighted_score
})
return sorted(content_scores, key=lambda x: x["score"], reverse=True)[:top_k]
except Exception as e:
logging.error(f"Error in content-based filtering for user {user_id}: {e}")
return []
# Define the class to receive the new user's preferences
class NewUserPreferences(BaseModel):
user_id: int
liked_categories: list
# Find the most similar user based on liked categories
def get_most_similar_user_by_categories(liked_categories):
if not liked_categories: # Ensure it's a valid list
return None
# Find users who bought products from the same categories
similar_users = preprocessed_df[
preprocessed_df["Product_Category"].isin(liked_categories)
]["user_id_idx"].value_counts()
logging.info(f"Most Similar Users: {similar_users}")
if not similar_users.empty:
return int(similar_users.idxmax()) # Most frequent user
return None
# Recommendation Function
def recommend(customer_id: str, top_k: int = 20, liked_categories: str = ""):
# Convert customer_id to user_id_idx
user_id = user_label_encoder.transform([customer_id])[0] if customer_id in user_label_encoder.classes_ else None
# Handle invalid customer_id
if user_id is None:
if not liked_categories:
return json.dumps({"error": "Customer ID not found. New users must provide liked categories"}, indent=2)
# Handle cold-start scenario for new users (new customer_id not in the dataset)
most_similar_user = get_most_similar_user_by_categories(liked_categories.split(','))
if most_similar_user is None:
logging.warning(f"No similar users found for liked categories: {liked_categories.split(',')}")
return json.dumps([], indent=2) # Return an empty list instead of hanging
# Use the most similar user for recommendations
user_id = most_similar_user
# Collaborative Filtering
logging.info("Starting collaborative filtering")
with torch.no_grad():
_, out = model(edge_index)
user_emb, item_emb = torch.split(out, (n_users, n_items))
user_embedding = user_emb[user_id]
collab_scores = torch.matmul(user_embedding, item_emb.T)
collab_top_k_indices = torch.topk(collab_scores, k=top_k).indices.tolist()
collab_recommendations = [
{
"item_id": int(item_id_mapping[idx]),
"product_name": product_name_mapping.get(idx, "Unknown"),
"score": float(collab_scores[idx])
}
for idx in collab_top_k_indices if idx in item_id_mapping
]
# Content-Based Filtering
content_recommendations = content_based_filtering(user_id, top_k)
# Hybrid Recommendation (Merging Scores)
hybrid_scores = {rec["item_id"]: rec["score"] for rec in collab_recommendations}
for rec in content_recommendations:
if rec["item_id"] in hybrid_scores:
hybrid_scores[rec["item_id"]] += rec["score"] # Merging scores
else:
hybrid_scores[rec["item_id"]] = rec["score"]
# Sort recommendations based on hybrid scores
hybrid_recommendations = sorted(
[{"item_id": item_id,"product_name": product_name_mapping.get(item_id, "Unknown"), "score": score} for item_id, score in hybrid_scores.items()],
key=lambda x: x["score"],
reverse=True
)[:top_k]
# Return top-k hybrid recommendations
return json.dumps(hybrid_recommendations, indent=2)
# import gradio as gr
# iface = gr.Interface(
# fn=recommend,
# inputs=[
# gr.Textbox(label="User ID"),
# gr.Number(label="Top K", value=20),
# gr.Textbox(label="Liked Categories (comma-separated)")
# ],
# outputs=gr.JSON(label="Recommendations"), # JSON output
# title="AI-Powered Product Recommendation System",
# description="Enter a user ID and get personalized product recommendations based on collaborative & content filtering."
# )
@app.get("/recommend/")
def get_recommendations(user_id: str, top_k: int = 20, liked_categories: str = ""):
result = recommend(user_id, top_k, liked_categories)
return JSONResponse(content=json.loads(result))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
# if __name__ == "__main__":
# iface.launch(server_name="0.0.0.0", server_port=7860)
|