55 lines
2.2 KiB
Python
55 lines
2.2 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 _new(self, material):
|
|
for row in self.curr_recommendations:
|
|
print(row)
|
|
if row['id'] == material['id'] and row['type'] == material['type']:
|
|
return False
|
|
return True
|
|
|
|
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 self._new(material):
|
|
print('hi')
|
|
self.curr_recommendations.append(material)
|
|
self.recommended.append(False)
|
|
|
|
def generate_recommendations(self, interests, new_material):
|
|
for interest in interests:
|
|
for i, material in new_material.iterrows():
|
|
self._match_tags(material, interest)
|
|
|
|
def make_recommendation(self, user):
|
|
if len(self.curr_recommendations) == 0:
|
|
return ""
|
|
to_consider = [idx for idx, value in enumerate(self.recommended) if value == False]
|
|
if len(to_consider) == 0:
|
|
return ""
|
|
index = random.choice(list(range(0, len(to_consider))))
|
|
index = self.recommended[index]
|
|
#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
|
|
|
|
|