ZEROTSUDIOS commited on
Commit
209b7fa
·
verified ·
1 Parent(s): e1f7ca9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -0
app.py CHANGED
@@ -79,6 +79,31 @@ class BookRecommender:
79
  logger.error(f"Error loading model: {str(e)}", exc_info=True)
80
  return False
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  def load_ood_thresholds(model_path):
83
  threshold_path = os.path.join(model_path, "ood_thresholds.json")
84
  if os.path.exists(threshold_path):
 
79
  logger.error(f"Error loading model: {str(e)}", exc_info=True)
80
  return False
81
 
82
+ def recommend_books(self, user_query, top_n=5, include_description=True):
83
+ if self.model is None or self.book_embeddings is None or self.df is None:
84
+ return []
85
+ try:
86
+ processed_query = self.preprocess_text(user_query)
87
+ user_embedding = self.model.encode([processed_query])
88
+ similarities = cosine_similarity(user_embedding, self.book_embeddings)[0]
89
+ similar_books_idx = np.argsort(similarities)[-top_n:][::-1]
90
+ recommendations = []
91
+ for i, idx in enumerate(similar_books_idx):
92
+ book_data = {
93
+ 'title': self.df.iloc[idx].get('Title', ''),
94
+ 'author': self.df.iloc[idx].get('Authors', ''),
95
+ 'category': self.df.iloc[idx].get('Category', ''),
96
+ 'year': self.df.iloc[idx].get('Publish Date (Year)', ''),
97
+ 'description': self.df.iloc[idx].get('Description', '')[:197] + "..." if include_description and 'Description' in self.df.columns else '',
98
+ 'relevance_score': float(similarities[idx]),
99
+ 'rank': i + 1
100
+ }
101
+ recommendations.append(book_data)
102
+ return recommendations
103
+ except Exception as e:
104
+ logger.error(f"Error generating recommendations: {str(e)}", exc_info=True)
105
+ return []
106
+
107
  def load_ood_thresholds(model_path):
108
  threshold_path = os.path.join(model_path, "ood_thresholds.json")
109
  if os.path.exists(threshold_path):