Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,168 +1,184 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import pickle
|
| 3 |
-
import polars as pl
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
st.
|
| 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 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
#
|
| 92 |
-
st.
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
if
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
st.
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
st.
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
st.
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pickle
|
| 3 |
+
import polars as pl
|
| 4 |
+
import re
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import numpy as np
|
| 7 |
+
from collections import Counter
|
| 8 |
+
|
| 9 |
+
st.set_page_config(page_title="Book Recommendation Engine", layout="wide")
|
| 10 |
+
|
| 11 |
+
@st.cache_resource
|
| 12 |
+
def load_models():
|
| 13 |
+
# Load the TF-IDF vectorizer
|
| 14 |
+
with open('tfidf_vectorizer.pkl', 'rb') as f:
|
| 15 |
+
tfidf = pickle.load(f)
|
| 16 |
+
|
| 17 |
+
# Load the KNN model
|
| 18 |
+
with open('knn_model.pkl', 'rb') as f:
|
| 19 |
+
knn_model = pickle.load(f)
|
| 20 |
+
|
| 21 |
+
return tfidf, knn_model
|
| 22 |
+
|
| 23 |
+
@st.cache_data
|
| 24 |
+
def load_data():
|
| 25 |
+
# Load the dataset
|
| 26 |
+
df_lazy = pl.scan_csv('goodreadsV5.csv')
|
| 27 |
+
df_cleaned = (
|
| 28 |
+
df_lazy.drop_nulls(subset=['name', 'summary', 'genres'])
|
| 29 |
+
.with_columns([
|
| 30 |
+
(pl.col('summary') + ' ' + pl.col('genres')).alias('combined_features')
|
| 31 |
+
])
|
| 32 |
+
).collect()
|
| 33 |
+
|
| 34 |
+
# Apply preprocessing to create the 'processed_features' column
|
| 35 |
+
df_cleaned = df_cleaned.with_columns([
|
| 36 |
+
pl.col('combined_features')
|
| 37 |
+
.map_elements(preprocess_text, return_dtype=pl.Utf8)
|
| 38 |
+
.alias('processed_features')
|
| 39 |
+
])
|
| 40 |
+
|
| 41 |
+
# Convert to pandas for easier indexing with KNN results
|
| 42 |
+
df_pandas = df_cleaned.to_pandas()
|
| 43 |
+
|
| 44 |
+
return df_cleaned, df_pandas
|
| 45 |
+
|
| 46 |
+
# Define the preprocessing function
|
| 47 |
+
def preprocess_text(text):
|
| 48 |
+
return re.sub(r'[^a-zA-Z0-9\s]', '', text.lower())
|
| 49 |
+
|
| 50 |
+
# Recommendation function for out-of-dataset books
|
| 51 |
+
def recommend_books_knn_out_of_dataset(df_pandas, tfidf, knn_model, input_summary, input_genres, top_n=5):
|
| 52 |
+
# Combine and preprocess the input book's features
|
| 53 |
+
combined_input = f"{input_summary} {input_genres}"
|
| 54 |
+
processed_input = preprocess_text(combined_input)
|
| 55 |
+
|
| 56 |
+
# Transform the input book's features using the loaded TF-IDF vectorizer
|
| 57 |
+
input_vector = tfidf.transform([processed_input])
|
| 58 |
+
|
| 59 |
+
# Find the nearest neighbors using the loaded KNN model
|
| 60 |
+
distances, indices = knn_model.kneighbors(input_vector, n_neighbors=top_n)
|
| 61 |
+
|
| 62 |
+
# Retrieve the recommended book information using pandas DataFrame
|
| 63 |
+
recommendations = []
|
| 64 |
+
for i, idx in enumerate(indices.flatten()):
|
| 65 |
+
book = {
|
| 66 |
+
"title": df_pandas.iloc[idx]['name'],
|
| 67 |
+
"summary": df_pandas.iloc[idx]['summary'],
|
| 68 |
+
"genres": df_pandas.iloc[idx]['genres'],
|
| 69 |
+
"similarity_score": 1 - distances.flatten()[i] # Convert distance to similarity score
|
| 70 |
+
}
|
| 71 |
+
recommendations.append(book)
|
| 72 |
+
|
| 73 |
+
return recommendations
|
| 74 |
+
|
| 75 |
+
def main():
|
| 76 |
+
st.title("π Book Recommendation Engine")
|
| 77 |
+
|
| 78 |
+
# Initialize session state variables if they don't exist
|
| 79 |
+
if 'example_summary' not in st.session_state:
|
| 80 |
+
st.session_state['example_summary'] = ""
|
| 81 |
+
if 'example_genres' not in st.session_state:
|
| 82 |
+
st.session_state['example_genres'] = ""
|
| 83 |
+
if 'run_example' not in st.session_state:
|
| 84 |
+
st.session_state['run_example'] = False
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
# Load models and data
|
| 88 |
+
tfidf, knn_model = load_models()
|
| 89 |
+
df_cleaned, df_pandas = load_data()
|
| 90 |
+
|
| 91 |
+
# Pre-fill with example if one was selected
|
| 92 |
+
default_summary = st.session_state['example_summary'] if st.session_state['run_example'] else "A fantasy adventure about a young wizard learning magic."
|
| 93 |
+
default_genres = st.session_state['example_genres'] if st.session_state['run_example'] else "fantasy, adventure, magic"
|
| 94 |
+
|
| 95 |
+
# Main content
|
| 96 |
+
st.subheader("Find Book Recommendations")
|
| 97 |
+
st.write("Enter a book summary and genres to get personalized recommendations.")
|
| 98 |
+
|
| 99 |
+
col1, col2 = st.columns(2)
|
| 100 |
+
|
| 101 |
+
with col1:
|
| 102 |
+
input_summary = st.text_area("Book Summary", default_summary, height=150)
|
| 103 |
+
|
| 104 |
+
with col2:
|
| 105 |
+
input_genres = st.text_input("Genres (comma-separated)", default_genres)
|
| 106 |
+
num_recommendations = st.slider("Number of Recommendations",
|
| 107 |
+
min_value=1, max_value=20, value=5)
|
| 108 |
+
|
| 109 |
+
# Display recommendations immediately if example was selected
|
| 110 |
+
if st.session_state['run_example'] or st.button("Get Recommendations", type="primary"):
|
| 111 |
+
with st.spinner("Finding the best book matches for you..."):
|
| 112 |
+
# Use the current input values, which may come from examples or user input
|
| 113 |
+
recommendations = recommend_books_knn_out_of_dataset(
|
| 114 |
+
df_pandas, tfidf, knn_model, input_summary, input_genres, num_recommendations
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
st.subheader("π Your Recommended Books")
|
| 118 |
+
|
| 119 |
+
for i, book in enumerate(recommendations):
|
| 120 |
+
with st.expander(f"{i+1}. {book['title']}"):
|
| 121 |
+
st.markdown(f"**Summary:** {book['summary']}")
|
| 122 |
+
st.markdown(f"**Genres:** {book['genres']}")
|
| 123 |
+
|
| 124 |
+
# Reset the example flag so it doesn't run again on rerender
|
| 125 |
+
st.session_state['run_example'] = False
|
| 126 |
+
|
| 127 |
+
# Example tabs section
|
| 128 |
+
st.subheader("Try these examples")
|
| 129 |
+
example_tabs = st.tabs(["Fantasy Adventure", "Romance", "Science Fiction", "Mystery"])
|
| 130 |
+
|
| 131 |
+
def set_example(summary, genres):
|
| 132 |
+
st.session_state['example_summary'] = summary
|
| 133 |
+
st.session_state['example_genres'] = genres
|
| 134 |
+
st.session_state['run_example'] = True
|
| 135 |
+
st.rerun()
|
| 136 |
+
|
| 137 |
+
with example_tabs[0]:
|
| 138 |
+
st.write("A magical journey through enchanted lands with dragons and wizards.")
|
| 139 |
+
st.write("Genres: fantasy, adventure, magic")
|
| 140 |
+
if st.button("Use this example", key="ex1"):
|
| 141 |
+
set_example(
|
| 142 |
+
"A magical journey through enchanted lands with dragons and wizards.",
|
| 143 |
+
"fantasy, adventure, magic"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
with example_tabs[1]:
|
| 147 |
+
st.write("A love story between two people from different worlds who meet by chance.")
|
| 148 |
+
st.write("Genres: romance, contemporary, drama")
|
| 149 |
+
if st.button("Use this example", key="ex2"):
|
| 150 |
+
set_example(
|
| 151 |
+
"A love story between two people from different worlds who meet by chance.",
|
| 152 |
+
"romance, contemporary, drama"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
with example_tabs[2]:
|
| 156 |
+
st.write("Space explorers discover an alien civilization that challenges their understanding of humanity.")
|
| 157 |
+
st.write("Genres: science fiction, space, aliens")
|
| 158 |
+
if st.button("Use this example", key="ex3"):
|
| 159 |
+
set_example(
|
| 160 |
+
"Space explorers discover an alien civilization that challenges their understanding of humanity.",
|
| 161 |
+
"science fiction, space, aliens"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
with example_tabs[3]:
|
| 165 |
+
st.write("A detective investigates a series of mysterious disappearances in a small town.")
|
| 166 |
+
st.write("Genres: mystery, thriller, crime")
|
| 167 |
+
if st.button("Use this example", key="ex4"):
|
| 168 |
+
set_example(
|
| 169 |
+
"A detective investigates a series of mysterious disappearances in a small town.",
|
| 170 |
+
"mystery, thriller, crime"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
except Exception as e:
|
| 174 |
+
st.error(f"An error occurred: {e}")
|
| 175 |
+
st.info("Make sure you have the required model files (tfidf_vectorizer.pkl, knn_model.pkl) and dataset (goodreadsV2.csv) in the same directory as this app.")
|
| 176 |
+
st.code("""
|
| 177 |
+
# Files needed:
|
| 178 |
+
- tfidf_vectorizer.pkl: Your trained TF-IDF vectorizer
|
| 179 |
+
- knn_model.pkl: Your trained KNN model
|
| 180 |
+
- goodreadsV2.csv: Your dataset with book information
|
| 181 |
+
""")
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
main()
|