File size: 4,288 Bytes
93c1744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
93
94
95
96
97
98
99
100
101
102
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()