douccana's picture
Upload 7 files
c8c34ef verified
Raw History Blame Contribute Delete
12.8 kB
#!/usr/bin/env python3
"""
AI Recommendation Engine using Trained SVD Model
This script loads a trained Surprise SVD model and generates personalized recommendations.
"""
import sys
import json
import pickle
import os
import random
import requests
from pathlib import Path
# Add the current directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
def get_supabase_client():
"""Get Supabase client using environment variables."""
try:
from supabase import create_client, Client
supabase_url = os.getenv('NEXT_PUBLIC_SUPABASE_URL')
supabase_key = os.getenv('SUPABASE_SERVICE_KEY')
if not supabase_url or not supabase_key:
print("Supabase environment variables not found", file=sys.stderr)
return None
supabase: Client = create_client(supabase_url, supabase_key)
return supabase
except ImportError:
print("supabase-py not installed, trying alternative approach", file=sys.stderr)
return None
except Exception as e:
print(f"Error creating Supabase client: {e}", file=sys.stderr)
return None
def load_model(model_path):
"""Load the trained SVD model from pickle file."""
try:
with open(model_path, 'rb') as f:
loaded_data = pickle.load(f)
# Check if it's a dictionary (model parameters) and try to reconstruct
if isinstance(loaded_data, dict):
print(f"Loaded model parameters from {model_path}", file=sys.stderr)
print(f"Parameter keys: {list(loaded_data.keys())}", file=sys.stderr)
try:
# Check if we have the actual trained model in the 'algo' key
if 'algo' in loaded_data and hasattr(loaded_data['algo'], 'predict'):
print("Found trained model in 'algo' key", file=sys.stderr)
return loaded_data['algo']
# Try to reconstruct the model from parameters
from surprise import SVD
model = SVD()
# Set the model parameters if they exist
if 'n_factors' in loaded_data:
model.n_factors = loaded_data['n_factors']
if 'n_epochs' in loaded_data:
model.n_epochs = loaded_data['n_epochs']
if 'lr_all' in loaded_data:
model.lr_all = loaded_data['lr_all']
if 'reg_all' in loaded_data:
model.reg_all = loaded_data['reg_all']
# Set the trained parameters if they exist
if 'pu' in loaded_data:
model.pu = loaded_data['pu']
if 'qi' in loaded_data:
model.qi = loaded_data['qi']
if 'bu' in loaded_data:
model.bu = loaded_data['bu']
if 'bi' in loaded_data:
model.bi = loaded_data['bi']
print("Model reconstructed from parameters successfully", file=sys.stderr)
return model
except ImportError:
print("Surprise library not available, cannot reconstruct model", file=sys.stderr)
return None
except Exception as e:
print(f"Error reconstructing model from parameters: {e}", file=sys.stderr)
return None
# Check if it's already a valid model
elif hasattr(loaded_data, 'predict') and callable(getattr(loaded_data, 'predict')):
print(f"Model loaded successfully from {model_path}", file=sys.stderr)
return loaded_data
else:
print(f"Error: Loaded object is not a valid model (type: {type(loaded_data)})", file=sys.stderr)
print("Object attributes:", dir(loaded_data), file=sys.stderr)
print("Using mock recommendation system instead", file=sys.stderr)
return None
except FileNotFoundError:
print(f"Error: Model file not found at {model_path}", file=sys.stderr)
print("Model loading failed", file=sys.stderr)
return None
except Exception as e:
print(f"Error loading model: {e}", file=sys.stderr)
print("Model loading failed", file=sys.stderr)
return None
def get_user_interactions(user_id):
"""Get user interactions from database using Supabase."""
supabase = get_supabase_client()
if not supabase:
print("Supabase client not available", file=sys.stderr)
return []
try:
# Call the get_user_interactions function
response = supabase.rpc('get_user_interactions', {'input_user_id': int(user_id)}).execute()
if response.data:
interactions = []
for row in response.data:
interactions.append({
'product_id': row['product_id'],
'interaction_score': float(row['interaction_score'])
})
return interactions
else:
return []
except Exception as e:
print(f"Error getting user interactions: {e}", file=sys.stderr)
return []
def get_all_products():
"""Get all available products from database using Supabase."""
supabase = get_supabase_client()
if not supabase:
print("Supabase client not available", file=sys.stderr)
return []
try:
# Call the get_all_products function
response = supabase.rpc('get_all_products').execute()
if response.data:
return [row['product_id'] for row in response.data]
else:
return []
except Exception as e:
print(f"Error getting all products: {e}", file=sys.stderr)
return []
def get_products_with_details(product_ids):
"""Get product details from database using Supabase."""
supabase = get_supabase_client()
if not supabase:
print("Supabase client not available", file=sys.stderr)
return []
try:
# Call the get_products_with_details function
response = supabase.rpc('get_products_with_details', {'product_ids': product_ids}).execute()
if response.data:
return response.data
else:
return []
except Exception as e:
print(f"Error getting product details: {e}", file=sys.stderr)
return []
def get_ai_recommendations(model, user_id, top_n=10, exclude_product_ids=None):
"""Generate AI recommendations using the trained SVD model."""
try:
print(f"Generating AI recommendations for user {user_id}, top_n={top_n}", file=sys.stderr)
# Get user interactions
user_interactions = get_user_interactions(user_id)
print(f"Got {len(user_interactions)} user interactions", file=sys.stderr)
# Get all available products
all_products = get_all_products()
print(f"Got {len(all_products)} total products", file=sys.stderr)
if not all_products:
return []
# Get products user has already interacted with (for penalty scoring)
interacted_products = {interaction['product_id'] for interaction in user_interactions}
# Use ALL products, but give penalty to already-interacted ones
all_products_for_prediction = all_products
# Exclude previously shown products if provided
if exclude_product_ids:
original_count = len(all_products_for_prediction)
all_products_for_prediction = [pid for pid in all_products_for_prediction if pid not in exclude_product_ids]
excluded_count = original_count - len(all_products_for_prediction)
print(f"Excluded {excluded_count} previously shown products", file=sys.stderr)
print(f"Using {len(all_products_for_prediction)} products (interacted: {len(interacted_products)}, excluded: {exclude_product_ids or []})", file=sys.stderr)
if not all_products_for_prediction:
return []
# AI predicts ratings for all products
predictions = []
for product_id in all_products_for_prediction:
try:
if model is None or not hasattr(model, 'predict'):
print(f"Model is not available for prediction, skipping product {product_id}", file=sys.stderr)
continue
pred = model.predict(str(user_id), str(product_id))
predicted_rating = float(pred.est)
# Check if user already interacted with this product
already_interacted = product_id in interacted_products
# Apply penalty for already-interacted products (50% reduction)
if already_interacted:
predicted_rating *= 0.5
print(f"Applied penalty for already-interacted product {product_id}", file=sys.stderr)
print(f"AI predicted rating: {predicted_rating} for product {product_id}, already_interacted: {already_interacted}", file=sys.stderr)
predictions.append((product_id, predicted_rating))
except Exception as e:
print(f"Error predicting for product {product_id}: {e}", file=sys.stderr)
continue
# Sort by predicted rating (descending)
predictions.sort(key=lambda x: x[1], reverse=True)
# Get top N product IDs
top_product_ids = [p[0] for p in predictions[:top_n]]
# Get product details
product_details = get_products_with_details(top_product_ids)
# Combine predictions with product details
recommendations = []
for i, (product_id, predicted_rating) in enumerate(predictions[:top_n]):
product_detail = next((p for p in product_details if p['product_id'] == product_id), None)
if product_detail:
# Extract data from the rich product_info structure
product_info = product_detail.get('product_info', {})
variations = product_detail.get('variations', [])
vendor_info = product_detail.get('vendor_info', {})
recommendations.append({
"product_id": product_id,
"ai_predicted_rating": round(predicted_rating, 3),
"engagement_score": float(product_detail.get('engagement_score', 0)),
"quality_score": int(product_detail.get('quality_score', 0)),
"product": {
"name": product_info.get('name', ''),
"description": product_info.get('description', ''),
"base_price": float(product_info.get('base_price', 0)),
"sale_price": float(product_info.get('sale_price', 0)) if product_info.get('sale_price') else None,
"product_type": product_info.get('product_type', ''),
"image_urls": product_info.get('image_urls', []),
"like_count": product_info.get('like_count', 0),
"view_count": product_info.get('view_count', 0),
"created_at": product_info.get('created_at', ''),
"promotion": product_info.get('promotion')
},
"variations": variations,
"vendor": {
"id": vendor_info.get('id'),
"name": vendor_info.get('name', ''),
"type": vendor_info.get('type', ''),
"profile_image_url": vendor_info.get('profile_image_url', ''),
"city": vendor_info.get('city', ''),
"commission_rate": vendor_info.get('commission_rate', 0),
"total_sales": vendor_info.get('total_sales', 0),
"approved": vendor_info.get('approved', False)
}
})
return recommendations
except Exception as e:
print(f"Error in AI recommendations: {e}", file=sys.stderr)
return []