luthrabhuvan commited on
Commit
9a51b24
·
verified ·
1 Parent(s): 9408787

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.feature_extraction.text import TfidfVectorizer
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+ import gradio as gr
5
+
6
+ class BookRecommender:
7
+ def __init__(self):
8
+ self.df = None
9
+ self.similarity_matrix = None
10
+
11
+ def load_data(self, file_obj):
12
+ try:
13
+ if file_obj.name.endswith('.csv'):
14
+ df = pd.read_csv(file_obj)
15
+ elif file_obj.name.endswith(('.xls', '.xlsx')):
16
+ df = pd.read_excel(file_obj)
17
+ else:
18
+ raise ValueError("Unsupported file format. Please provide a CSV or Excel file.")
19
+ return df
20
+ except Exception as e:
21
+ return str(e)
22
+
23
+ def preprocess_data(self, df):
24
+ df['summary'] = df['summary'].fillna('')
25
+ df['title'] = df['title'].fillna('')
26
+ df = df.drop_duplicates(subset=['title', 'summary'])
27
+ return df
28
+
29
+ def create_tfidf_matrix(self, df):
30
+ tfidf = TfidfVectorizer(stop_words='english')
31
+ tfidf_matrix = tfidf.fit_transform(df['summary'])
32
+ return tfidf_matrix
33
+
34
+ def calculate_similarity(self, tfidf_matrix):
35
+ return cosine_similarity(tfidf_matrix)
36
+
37
+ def recommend_books(self, book_title):
38
+ if self.df is None or self.similarity_matrix is None:
39
+ return ["Please upload and process a file first."]
40
+ try:
41
+ book_index = self.df[self.df['title'] == book_title].index[0]
42
+ except IndexError:
43
+ return ["Book title not found."]
44
+
45
+ similar_books_indices = self.similarity_matrix[book_index].argsort()[::-1][1:6]
46
+ return self.df['title'].iloc[similar_books_indices].tolist()
47
+
48
+ def create_interface(self):
49
+ def process_file(file_obj):
50
+ if file_obj is None:
51
+ return "Please upload a file first.", None
52
+ self.df = self.load_data(file_obj)
53
+ self.df = self.preprocess_data(self.df)
54
+ tfidf_matrix = self.create_tfidf_matrix(self.df)
55
+ self.similarity_matrix = self.calculate_similarity(tfidf_matrix)
56
+ return "File uploaded and processed successfully!", gr.update(interactive=True)
57
+
58
+ def recommend_interface(book_title):
59
+ recommendations = self.recommend_books(book_title)
60
+ return recommendations
61
+
62
+ with gr.Blocks() as iface:
63
+ file_input = gr.File(label="Upload CSV or Excel file")
64
+ process_button = gr.Button("Process File")
65
+ status_text = gr.Textbox(label="Status", interactive=False)
66
+ text_input = gr.Textbox(lines=1, placeholder="Enter book title", interactive=False)
67
+ output_list = gr.Textbox(label="Recommended Books", interactive=False)
68
+
69
+ process_button.click(process_file, inputs=file_input, outputs=[status_text, text_input])
70
+ text_input.submit(recommend_interface, inputs=text_input, outputs=output_list)
71
+
72
+ return iface
73
+
74
+ recommender = BookRecommender()
75
+ interface = recommender.create_interface()
76
+ interface.launch()