luthrabhuvan's picture
Create app.py
93c1744 verified
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import gradio as gr
class BookRecommender:
def __init__(self):
self.df = None
self.similarity_matrix = None
def load_data(self, filepath):
try:
if filepath.endswith('.csv'):
df = pd.read_csv(filepath)
elif filepath.endswith(('.xls', '.xlsx')):
df = pd.read_excel(filepath)
else:
raise ValueError("Unsupported file format. Please provide a CSV or Excel file.")
return df
except FileNotFoundError:
raise FileNotFoundError(f"File not found at {filepath}")
except ValueError as e:
raise ValueError(f"Error loading data: {e}")
except Exception as e:
raise Exception(f"Error loading data: {e}")
def preprocess_data(self, df, summary_column='summary', title_column='title'):
if df[summary_column].isnull().any():
df[summary_column] = df[summary_column].fillna('')
print("Handled missing values in summary column.")
if df[title_column].isnull().any():
df[title_column] = df[title_column].fillna('')
print("Handled missing values in title column.")
df = df.drop_duplicates(subset=[title_column, summary_column], keep='first')
print("Removed duplicate rows.")
df = df[~(df[title_column] == '') | (df[summary_column] == '')]
print("Removed rows with blank title and summary.")
return df
def create_tfidf_matrix(self, df, summary_column='summary'):
tfidf = TfidfVectorizer(stop_words='english')
tfidf_matrix = tfidf.fit_transform(df[summary_column])
return tfidf_matrix, tfidf
def calculate_similarity(self, tfidf_matrix):
similarity_matrix = cosine_similarity(tfidf_matrix)
return similarity_matrix
def recommend_books(self, book_title):
try:
book_index = self.df[self.df['title'] == book_title].index[0]
except IndexError:
return "Book title not found."
except Exception as e:
return f"An error occurred: {e}"
similar_books_indices = self.similarity_matrix[book_index].argsort()[::-1][1:6] # Fixed top_n to 5
recommended_books = self.df['title'].iloc[similar_books_indices].tolist()
return recommended_books
def create_interface(self):
def upload_and_process(file_obj):
if file_obj is None:
return "Please upload a file first.", None
filepath = file_obj.name
try:
self.df = self.load_data(filepath)
self.df = self.preprocess_data(self.df)
tfidf_matrix, _ = self.create_tfidf_matrix(self.df)
self.similarity_matrix = self.calculate_similarity(tfidf_matrix)
return "File uploaded and processed successfully!", gr.update(interactive=True)
except Exception as e:
return f"Error: {e}", None
def recommend_book_interface(book_title):
if self.df is None or self.similarity_matrix is None:
return "Please upload and process a file first."
recommendations = self.recommend_books(book_title)
formatted_recommendations = [[rec] for rec in recommendations]
return formatted_recommendations
with gr.Blocks() as iface:
file_output = gr.File(label="Upload CSV or Excel file", file_types=[".csv", ".xls", ".xlsx"])
process_button = gr.Button("Process File")
status_text = gr.Textbox(label="Status")
text_input = gr.Textbox(lines=1, placeholder="Enter book title", interactive=False)
output_list = gr.List(label="Recommended Books")
process_button.click(upload_and_process, inputs=file_output, outputs=[status_text, text_input])
text_input.change(recommend_book_interface, inputs=text_input, outputs=output_list)
return iface # Correct indentation here
if __name__ == '__main__':
recommender = BookRecommender()
interface = recommender.create_interface()
interface.launch()