|
import pandas as pd |
|
from sentence_transformers import SentenceTransformer |
|
import faiss |
|
|
|
class ProductRecommender: |
|
def __init__(self, product_data_path): |
|
try: |
|
|
|
self.data = pd.read_csv(product_data_path) |
|
print("Product data loaded successfully.") |
|
except Exception as e: |
|
print(f"Error loading product data: {e}") |
|
self.data = pd.DataFrame() |
|
return |
|
|
|
try: |
|
|
|
self.model = SentenceTransformer('all-MiniLM-L6-v2') |
|
print("Model loaded successfully.") |
|
except Exception as e: |
|
print(f"Error loading SentenceTransformer model: {e}") |
|
self.model = None |
|
return |
|
|
|
try: |
|
|
|
if 'product_description' not in self.data.columns: |
|
print("Error: 'product_description' column is missing in the data.") |
|
return |
|
|
|
|
|
self.embeddings = self.model.encode(self.data['product_description'].tolist()) |
|
print(f"Embeddings generated successfully. Shape: {self.embeddings.shape}") |
|
except Exception as e: |
|
print(f"Error generating embeddings: {e}") |
|
self.embeddings = None |
|
return |
|
|
|
try: |
|
|
|
self.index = faiss.IndexFlatL2(self.embeddings.shape[1]) |
|
self.index.add(self.embeddings) |
|
print("FAISS index created and embeddings added.") |
|
except Exception as e: |
|
print(f"Error creating FAISS index or adding embeddings: {e}") |
|
self.index = None |
|
return |
|
|
|
def get_recommendations(self, query, top_n=5): |
|
if self.model is None or self.index is None: |
|
print("Error: Model or FAISS index not initialized. Cannot make recommendations.") |
|
return [] |
|
|
|
try: |
|
|
|
query_embedding = self.model.encode([query]) |
|
print(f"Query embedding generated. Shape: {query_embedding.shape}") |
|
except Exception as e: |
|
print(f"Error generating query embedding: {e}") |
|
return [] |
|
|
|
try: |
|
|
|
distances, indices = self.index.search(query_embedding, top_n) |
|
recommendations = [] |
|
for i in indices[0]: |
|
recommendations.append(self.data.iloc[i]['product_title'] + ": " + self.data.iloc[i]['product_description']) |
|
print(f"Recommendations generated successfully: {recommendations}") |
|
return recommendations |
|
except Exception as e: |
|
print(f"Error during recommendation search: {e}") |
|
return [] |
|
|