Spaces:
Sleeping
Sleeping
Download app.py from basaktamer/Book_Recommender: direct link, hf CLI and curl.
- Browser
- Download file 4.08 kB
-
https://huggingface.co/spaces/basaktamer/Book_Recommender/resolve/main/app.py
- Command line
-
hf download hf://spaces/basaktamer/Book_Recommender/app.py
-
curl -L -o app.py https://huggingface.co/spaces/basaktamer/Book_Recommender/resolve/main/app.py
4.08 kB
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| from scipy import spatial | |
| import operator | |
| # --- 1. APP CONFIGURATION --- | |
| st.set_page_config( | |
| page_title="Book Recommender KNN DS20", | |
| page_icon="๐", | |
| layout="wide" | |
| ) | |
| # --- 2. DATA LOADING & CACHING --- | |
| def load_and_clean_data(): | |
| # Loading the dataset (ensure books.csv is in your project folder) | |
| df = pd.read_csv('books.csv', on_bad_lines='skip') | |
| df.columns = df.columns.str.strip() | |
| # Selecting essential columns to save 8GB RAM | |
| slim_df = df[['bookID', 'title', 'authors', 'average_rating', 'ratings_count', 'language_code']].copy() | |
| # Building the Global Popularity/Mean map | |
| mp = slim_df.groupby('bookID').agg({'ratings_count': 'sum', 'average_rating': 'mean'}) | |
| mp.columns = ['size', 'mean'] | |
| return slim_df, mp | |
| # --- 3. THE RECOMMENDATION ENGINE --- | |
| def compute_distance(a, b): | |
| # a/b format: (name, features, size, mean) | |
| # Feature Distance (Authors/Language) | |
| genre_dist = spatial.distance.cosine(a[1], b[1]) | |
| # Popularity Distance (Ratings Count) | |
| pop_dist = abs(a[2] - b[2]) | |
| return genre_dist + pop_dist | |
| def get_neighbors(book_id, book_dict, k=5): | |
| distances = [] | |
| for b_id in book_dict: | |
| if b_id != book_id: | |
| dist = compute_distance(book_dict[book_id], book_dict[b_id]) | |
| distances.append((b_id, dist)) | |
| # Sort by lowest distance | |
| distances.sort(key=operator.itemgetter(1)) | |
| return [d[0] for d in distances[:k]] | |
| # --- 4. MAIN APP LOGIC --- | |
| def main(): | |
| st.title("๐ AI Book Discovery Engine") | |
| st.markdown("---") | |
| # Metrics Row | |
| c1, c2, c3 = st.columns(3) | |
| c1.metric("Model Accuracy (MAE)", "0.2927", delta="-0.05", delta_color="inverse") | |
| c2.metric("Knowledge Base", "10,812 Books") | |
| c3.metric("Algorithm", "Hybrid KNN") | |
| # Load data | |
| df, mp = load_and_clean_data() | |
| # Build Dictionary (Cached within the session) | |
| unique_authors = list(df['authors'].unique()) | |
| unique_langs = list(df['language_code'].unique()) | |
| # Note: Building this once per app-load | |
| if 'book_dict' not in st.session_state: | |
| with st.spinner("Constructing KNN Dictionary..."): | |
| temp_dict = {} | |
| for index, row in df.iterrows(): | |
| b_id = int(row['bookID']) | |
| features = [0] * (len(unique_authors) + len(unique_langs)) | |
| features[unique_authors.index(row['authors'])] = 1 | |
| features[len(unique_authors) + unique_langs.index(row['language_code'])] = 1 | |
| temp_dict[b_id] = ( | |
| row['title'], | |
| features, | |
| mp.loc[b_id, 'size'], | |
| mp.loc[b_id, 'mean'] | |
| ) | |
| st.session_state.book_dict = temp_dict | |
| # User Interface | |
| st.sidebar.header("Search Settings") | |
| k_value = st.sidebar.slider("Number of recommendations:", 3, 10, 5) | |
| selected_title = st.selectbox( | |
| "Which book did you enjoy recently?", | |
| df['title'].unique(), | |
| index=None, | |
| placeholder="Search for a title..." | |
| ) | |
| if selected_title: | |
| # Get the ID for the selected title | |
| target_id = df[df['title'] == selected_title]['bookID'].values[0] | |
| if st.button("Generate Recommendations"): | |
| with st.spinner("Analyzing neighbor nodes in feature space..."): | |
| neighbors = get_neighbors(target_id, st.session_state.book_dict, k=k_value) | |
| st.subheader(f"Because you liked '{selected_title}':") | |
| # Display results in columns | |
| cols = st.columns(k_value) | |
| for i, n_id in enumerate(neighbors): | |
| with cols[i]: | |
| st.success(f"**{st.session_state.book_dict[n_id][0]}**") | |
| st.write(f"โญ Rating: {st.session_state.book_dict[n_id][3]}") | |
| st.caption(f"Pop: {int(st.session_state.book_dict[n_id][2])}") | |
| if __name__ == "__main__": | |
| main() |