Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from EnYa32/BookRecommendation: direct link, hf CLI and curl.
- Browser
- Download file 1.75 kB
-
https://huggingface.co/spaces/EnYa32/BookRecommendation/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/EnYa32/BookRecommendation/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/EnYa32/BookRecommendation/resolve/main/src/streamlit_app.py
1.75 kB
| 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") | |
| 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.") |