Spaces:
No application file
No application file
import pickle | |
import numpy as np | |
from sentence_transformers import SentenceTransformer | |
from sklearn.metrics.pairwise import cosine_similarity | |
# Load model embeddings | |
with open("../models/product_embeddings.pkl", "rb") as f: | |
data = pickle.load(f) | |
# Load transformer model | |
model = SentenceTransformer('all-MiniLM-L6-v2') | |
def recommend_products(user_query, top_n=5): | |
"""Find similar products based on user search""" | |
query_embedding = model.encode(user_query).reshape(1, -1) | |
# Compute similarity scores | |
similarities = cosine_similarity(query_embedding, data["embeddings"]) | |
top_indices = np.argsort(similarities[0])[-top_n:][::-1] # Get top matches | |
recommendations = [] | |
for i in top_indices: | |
recommendations.append({ | |
"search_query": data["search_queries"][i], | |
"product": data["product_names"][i], | |
"score": float(similarities[0][i]) | |
}) | |
return recommendations | |
# Example test | |
if __name__ == "__main__": | |
query = "gaming laptop" | |
results = recommend_products(query) | |
for r in results: | |
print(f"🔹 {r['product']} (Score: {r['score']:.2f})") | |