File size: 1,746 Bytes
dd4284e
0f4ef32
 
 
 
b73b8fd
0f4ef32
 
b73b8fd
e521045
b73b8fd
 
2bee827
b73b8fd
 
 
0f4ef32
b73b8fd
0f4ef32
b73b8fd
 
 
 
 
0f4ef32
 
b73b8fd
 
0f4ef32
b73b8fd
 
0f4ef32
b73b8fd
 
0f4ef32
 
 
 
 
b73b8fd
 
 
0f4ef32
 
b73b8fd
 
0f4ef32
b73b8fd
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
44
45
46
47
48
import streamlit as st
import pandas as pd
import joblib
from scipy import spatial

st.set_page_config(page_title="Book Recommender", page_icon="๐Ÿ“š", layout="wide")

@st.cache_resource
def load_all():
    df = pd.read_csv("src/bookss_data.csv")
    df["average_rating"] = df["average_rating"].astype(float)
    df["content"] = df["title"] + " " + df["authors"]

    tf = joblib.load("src/tfidf_vectorizer.pkl")
    X = tf.transform(df["content"])
    return df, tf, X

df, tf, X = load_all()

def compute_distance(i, j, rating_weight=0.3):
    v1 = X[i].toarray().ravel()
    v2 = X[j].toarray().ravel()
    content_distance = spatial.distance.cosine(v1, v2)
    rating_distance = abs(df.loc[i, "average_rating"] - df.loc[j, "average_rating"]) * rating_weight
    return content_distance + rating_distance

def recommend(title, top_n=10, rating_weight=0.3):
    idx = df.index[df["title"] == title][0]
    distances = []
    for j in range(len(df)):
        if j == idx:
            continue
        d = compute_distance(idx, j, rating_weight=rating_weight)
        distances.append((df.loc[j,"bookID"], df.loc[j,"title"], df.loc[j,"average_rating"], d))
    distances.sort(key=lambda x: x[3])
    return distances[:top_n]

st.title("๐Ÿ“š Book Recommendation System")

selected_title = st.selectbox("Choose a book", sorted(df["title"].unique()))
top_n = st.slider("Top N", 3, 20, 10)
rating_weight = st.slider("Rating weight", 0.0, 1.0, 0.3, 0.05)

if st.button("Recommend"):
    recs = recommend(selected_title, top_n=top_n, rating_weight=rating_weight)
    rec_df = pd.DataFrame(recs, columns=["bookID","title","average_rating","distance"])
    st.dataframe(rec_df, use_container_width=True)
    st.caption("Smaller distance = more similar.")