Tirath5504
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
mport gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
5 |
+
|
6 |
+
pt = pickle.load(open('pt.pkl', 'rb'))
|
7 |
+
user_similarity_scores = pickle.load(open('user_similarity_scores.pkl', 'rb'))
|
8 |
+
|
9 |
+
def recommend_books_for_user(user_id):
|
10 |
+
"""Recommends books for a user based on collaborative filtering"""
|
11 |
+
user_index = pt.columns.get_loc(user_id)
|
12 |
+
|
13 |
+
similar_users = sorted(list(enumerate(user_similarity_scores[user_index])), key=lambda x: x[1], reverse=True)[1:5]
|
14 |
+
|
15 |
+
recommended_books = []
|
16 |
+
|
17 |
+
for similar_user_index, similarity_score in similar_users:
|
18 |
+
user_ratings = pt.iloc[:, user_index]
|
19 |
+
similar_user_ratings = pt.iloc[:, similar_user_index]
|
20 |
+
|
21 |
+
unrated_books = similar_user_ratings[(user_ratings == 0) & (similar_user_ratings > 0)]
|
22 |
+
|
23 |
+
recommended_books.extend(unrated_books.index)
|
24 |
+
|
25 |
+
return recommended_books
|
26 |
+
|
27 |
+
def recommend_books_gradio(user_id):
|
28 |
+
"""Recommends books for a user based on collaborative filtering"""
|
29 |
+
recommended_books = recommend_books_for_user(int(user_id))
|
30 |
+
return recommended_books
|
31 |
+
|
32 |
+
interface = gr.Interface(fn=recommend_books_gradio,
|
33 |
+
inputs=gr.Textbox(label="Enter User ID"),
|
34 |
+
outputs=gr.List(label="Recommended Books"),
|
35 |
+
title="Book Recommender System")
|
36 |
+
|
37 |
+
interface.launch()
|