Sadmanul/Collaborative-Filtering-Recommender-System
0
1import streamlit as st2import joblib3import time4 5# -------------------------------------------------6# Page config & title7# -------------------------------------------------8st.set_page_config(page_title="Book Recommender System", layout="wide")9st.title("Book Recommender System")10 11# -------------------------------------------------12# Load model (cached once)13# -------------------------------------------------14@st.cache_resource15def load_model():16 model = joblib.load("model.pkl")17 return {18 "data": model["data"],19 "similarity": model["similarity"],20 "pivot_index": model["pivot_index"],21 }22 23with st.spinner("Loading model and book catalogue..."):24 model_data = load_model()25 data = model_data["data"]26 similarity = model_data["similarity"]27 pivot_index = model_data["pivot_index"]28 29st.success(f"Loaded **{len(pivot_index):,}** books successfully!")30 31# -------------------------------------------------32# Safe image URL33# -------------------------------------------------34def safe_image_url(book_name: str) -> str:35 try:36 url = data[data["book_name"] == book_name].iloc[0]["image_url"]37 return url if url and isinstance(url, str) and url.strip() else "https://via.placeholder.com/120x180?text=No+Image"38 except:39 return "https://via.placeholder.com/120x180?text=No+Image"40 41# -------------------------------------------------42# Recommend 7 books43# -------------------------------------------------44def recommend(book_name: str):45 if book_name not in pivot_index:46 st.error("Book not found in the similarity dataset!")47 return []48 49 book_idx = pivot_index.index(book_name)50 distances = similarity[book_idx]51 similar_items = sorted(52 enumerate(distances), key=lambda x: x[1], reverse=True53 )[1:8] # Top 7 (skip itself)54 55 recs = []56 for idx, _ in similar_items:57 title = pivot_index[idx]58 img = safe_image_url(title)59 recs.append((title, img))60 return recs61 62# -------------------------------------------------63# UI: Book selector64# -------------------------------------------------65book_name = st.selectbox(66 "Select a book:",67 options=pivot_index,68 index=None,69 placeholder="Start typing or choose a book..."70)71 72# -------------------------------------------------73# Recommend button74# -------------------------------------------------75if st.button("Recommend"):76 if not book_name:77 st.warning("Please select a book first!")78 else:79 st.subheader("Recommended Books:")80 with st.spinner("Finding 7 similar books..."):81 time.sleep(0.6) # Optional: makes spinner visible82 recommendations = recommend(book_name)83 84 if recommendations:85 # Force image height to 180px86 st.markdown(87 """88 <style>89 .book-img img {90 height: 180px !important;91 width: auto !important;92 object-fit: contain;93 border-radius: 8px;94 box-shadow: 0 2px 6px rgba(0,0,0,0.1);95 }96 </style>97 """,98 unsafe_allow_html=True,99 )100 101 # 7 columns102 cols = st.columns(7, gap="medium")103 for i, (title, img_url) in enumerate(recommendations):104 with cols[i]:105 st.markdown(106 f'<div class="book-img"><img src="{img_url}"></div>',107 unsafe_allow_html=True,108 )109 st.caption(title, unsafe_allow_html=True)110 else:111 st.info("No recommendations found.")