File size: 1,447 Bytes
8f07d0e
f1a5823
491c0e0
 
f1a5823
 
 
 
e6cf2c9
f1a5823
 
 
 
 
 
 
e6cf2c9
f1a5823
 
 
 
 
 
e6cf2c9
f1a5823
e6cf2c9
f1a5823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import streamlit as st
import pandas as pd
import joblib

# ---------- Load Saved Model ----------
model = joblib.load("src/book_recommender_model.pkl")
scaler = joblib.load("src/scaler.pkl")
df = joblib.load("src/books_df.pkl")

# Recreate features_scaled for KNN lookup
features = pd.concat([
    pd.get_dummies(df["rating_between"]),
    pd.get_dummies(df["language_code"]),
    df[["average_rating","ratings_count"]]
], axis=1)
features_scaled = scaler.transform(features)

# ---------- Create indices ----------
indices = pd.Series(df.index, index=df["title"])

# ---------- Streamlit UI ----------
st.title("📚 Book Recommendation App")
st.write("Content-Based Recommendation System using pre-trained model")

title = st.selectbox("Select a book", df["title"].values)

def recommend(title, n=5):
    if title not in indices:
        return pd.DataFrame(columns=["Title","Authors","Average_Rating","Ratings_Count"])
    
    idx = indices[title]
    distances, neighbors_idx = model.kneighbors([features_scaled[idx]], n_neighbors=n+1)
    neighbors_idx = neighbors_idx[0][1:]  # exclude the book itself
    return df.iloc[neighbors_idx][["title","authors","average_rating","ratings_count"]]

if st.button("Recommend"):
    recommendations = recommend(title)
    if recommendations.empty:
        st.error("❌ Book not found")
    else:
        st.subheader("Recommended Books")
        st.dataframe(recommendations.reset_index(drop=True))