import gradio as gr import numpy as np import pandas as pd import pickle from sklearn.metrics.pairwise import cosine_similarity pt = pd.read_pickle('pt.pkl') user_similarity_scores = cosine_similarity(pt.T) books = pd.read_pickle("books.pkl") def recommend_books_for_user(user_id): user_index = pt.columns.get_loc(user_id) similar_users = sorted(list(enumerate(user_similarity_scores[user_index])), key=lambda x: x[1], reverse=True)[1:5] recommended_books = [] for similar_user_index, similarity_score in similar_users: user_ratings = pt.iloc[:, user_index] similar_user_ratings = pt.iloc[:, similar_user_index] unrated_books = similar_user_ratings[(user_ratings == 0) & (similar_user_ratings > 0)] recommended_books.extend(unrated_books.index) recommended_books_set = set(recommended_books) ans = [(book_title, image_url) for book_title, image_url in zip(books["Book-Title"], books["Image-URL-M"]) if book_title in recommended_books_set] return ans def recommend_books_gradio(user_id): """Recommends books for a user based on collaborative filtering""" recommended_books = recommend_books_for_user(int(user_id)) return [[book] for book in recommended_books] interface = gr.Interface(fn=recommend_books_gradio, inputs=gr.Textbox(label="Enter User ID"), outputs=gr.List(label="Recommended Books"), title="Book Recommender System") interface.launch()