Spaces:
Sleeping
Sleeping
import pickle | |
import streamlit as st | |
import numpy as np | |
st.header("Book Recommender System") | |
model = pickle.load(open("artifacts/model.pkl", "rb")) | |
book_names = pickle.load(open("artifacts/book_names.pkl", "rb")) | |
final_ratings = pickle.load(open("artifacts/final_ratings.pkl", "rb")) | |
book_pivot = pickle.load(open("artifacts/book_pivot.pkl", "rb")) | |
def fetch_poster(suggestion): | |
bookNames = [] | |
idsIndex = [] | |
posterUrl = [] | |
for bookId in suggestion[0]: | |
name = book_pivot.index[bookId] | |
bookNames.append(book_pivot.index[bookId]) | |
for name in bookNames: | |
ids = np.where(final_ratings['title'] == name)[0][0] | |
idsIndex.append(ids) | |
for idx in idsIndex: | |
row = final_ratings.iloc[idx] | |
url = row['img_url'] | |
posterUrl.append(url) | |
return posterUrl | |
def recommend_book(bookName): | |
bookList = [] | |
book_id = np.where(book_pivot.index == bookName)[0][0] | |
distance, suggestion = model.kneighbors(book_pivot.iloc[book_id,:].values.reshape(1, -1), n_neighbors=5) | |
poster_url = fetch_poster(suggestion) | |
for i in range(len(suggestion)): | |
books = book_pivot.index[suggestion[i]] | |
for j in books: | |
bookList.append(j) | |
return bookList, poster_url | |
selected_books = st.selectbox( | |
"Select a book", | |
book_names | |
) | |
if st.button("Show Recommendations"): | |
recommendations, posterUrls = recommend_book(selected_books) | |
st.subheader("Recommendations") | |
col1, col2, col3, col4 = st.columns(4) | |
for url in posterUrls: | |
print(url) | |
with col1: | |
st.text(recommendations[1]) | |
st.image(posterUrls[1]) | |
with col2: | |
st.text(recommendations[2]) | |
st.image(posterUrls[2]) | |
with col3: | |
st.text(recommendations[3]) | |
st.image(posterUrls[3]) | |
with col4: | |
st.text(recommendations[4]) | |
st.image(posterUrls[4]) |