JanetBackEnd/Recommender.py

55 lines
2.2 KiB
Python
Raw Normal View History

2023-03-30 15:17:54 +02:00
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
2023-04-09 22:43:13 +02:00
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
2023-03-30 15:17:54 +02:00
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:
2023-04-09 22:43:13 +02:00
if self._new(material):
print('hi')
2023-03-30 15:17:54 +02:00
self.curr_recommendations.append(material)
self.recommended.append(False)
def generate_recommendations(self, interests, new_material):
for interest in interests:
2023-04-09 22:43:13 +02:00
for i, material in new_material.iterrows():
2023-03-30 15:17:54 +02:00
self._match_tags(material, interest)
def make_recommendation(self, user):
if len(self.curr_recommendations) == 0:
return ""
2023-04-09 22:43:13 +02:00
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))))
2023-03-30 15:17:54 +02:00
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