Spaces:
Running
Running
| import streamlit as st | |
| import pickle | |
| import pandas as pd | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| # Load the model and necessary files | |
| def load_model(): | |
| with open("model2.pkl", "rb") as f: | |
| tfidf_matrix, vectorizer, similarity_matrix, df = pickle.load(f) | |
| return tfidf_matrix, vectorizer, similarity_matrix, df | |
| # Load the model | |
| tfidf_matrix, vectorizer, similarity_matrix, df = load_model() | |
| # Streamlit user interface | |
| st.title("Book Recommender System") | |
| # Input from the user | |
| title = st.text_input("Enter a book title:") | |
| # Function to get recommendations | |
| def get_recommendations(title, df, similarity_matrix): | |
| if title in df['book_name'].values: | |
| book_index = df[df['book_name'] == title].index[0] | |
| similarity_scores = list(enumerate(similarity_matrix[book_index])) | |
| similarity_scores = sorted(similarity_scores, key=lambda x: x[1], reverse=True)[1:6] | |
| recommendations = [] | |
| for i in similarity_scores: | |
| recommended_book = df.iloc[i[0]]['book_name'] | |
| if recommended_book != title and recommended_book not in recommendations: | |
| recommendations.append(recommended_book) | |
| return recommendations | |
| else: | |
| return ["Book not found in dataset."] | |
| # Show recommendations when the user inputs a title | |
| if title: | |
| recommendations = get_recommendations(title, df, similarity_matrix) | |
| st.write(f"Recommendations for '{title}':") | |
| for rec in recommendations: | |
| st.write(f"- {rec}") | |