JanetBackEnd/Recommender.py

43 lines
1.8 KiB
Python

import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import random
class Recommender:
def __init__(self, retriever):
self.curr_recommendations = []
self.recommended = []
self.retriever = retriever
self.rand_seed = 5
def _match_tags(self, material, interest):
score = 0.7
for tag in material['tags']:
if cosine_similarity(np.array(self.retriever.encode([tag])),
np.array(self.retriever.encode([interest]))) > score:
if material not in self.curr_recommendations:
self.curr_recommendations.append(material)
self.recommended.append(False)
def generate_recommendations(self, interests, new_material):
for interest in interests:
for material in new_material:
self._match_tags(material, interest)
def make_recommendation(self, user):
if len(self.curr_recommendations) == 0:
return ""
index = random.choice(list(range(0, len(self.curr_recommendations))))
while self.recommended[index] == True:
index = random.choice(list(range(0, len(self.curr_recommendations))))
recommendation = "Hey " + user + "! This " + self.curr_recommendations[index][
'type'].lower() + " about " + ', '.join(
self.curr_recommendations[index]['tags']).lower() + " was posted recently by " + \
self.curr_recommendations[index][
'author'].lower() + " on the catalogue. You may wanna check it out! It is titled " + \
self.curr_recommendations[index]['title'].lower() + ". Cheers, Janet"
# self.curr_recommendations.remove(self.curr_recommendations[index])
self.recommended[index] = True
return recommendation