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 _new(self, username, material): if username not in curr_recommendations: return True for row in self.curr_recommendations[username]: if row['id'] == material['id'] and row['type'] == material['type']: return False return True def _match_tags(self, username, 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 self._new(username, material): print('hi') self.curr_recommendations[username] = self.curr_recommendations[username].append(material) if username not in self.curr_recommendations else [material] self.recommended[username] = self.recommended[username].append(False) if username not in self.recommended else [False] def generate_recommendations(self, username, interests, new_material): for interest in interests: for i, material in new_material.iterrows(): self._match_tags(username, material, interest) def make_recommendation(self, username, name): if len(self.curr_recommendations[username]) == 0: return "" to_consider = [idx for idx, value in enumerate(self.recommended[username]) if value == False] if len(to_consider) == 0: return "" index = random.choice(list(range(0, len(to_consider)))) index = self.recommended[username][index] #while self.recommended[index] == True: # index = random.choice(list(range(0, len(self.curr_recommendations)))) recommendation = "Hey " + name + "! This " + self.curr_recommendations[username][index][ 'type'].lower() + " about " + ', '.join( self.curr_recommendations[username][index]['tags']).lower() + " was posted recently by " + \ self.curr_recommendations[username][index][ 'author'].lower() + " on the catalogue. You may wanna check it out! It is titled " + \ self.curr_recommendations[username][index]['title'].lower() + ". Cheers, Janet" # self.curr_recommendations.remove(self.curr_recommendations[index]) self.recommended[username][index] = True return recommendation