Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,202 +1,201 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import numpy as np
|
| 6 |
-
|
| 7 |
-
from typing import List, Tuple
|
| 8 |
-
import faiss
|
| 9 |
-
from faiss import write_index, read_index
|
| 10 |
-
import gradio as gr
|
| 11 |
-
from fuzzywuzzy import process
|
| 12 |
-
from pandas import DataFrame
|
| 13 |
-
from tqdm import tqdm
|
| 14 |
-
from transformers import BertTokenizerFast, BertModel, AutoTokenizer, AutoModel
|
| 15 |
-
|
| 16 |
-
# Global variables to store loaded data
|
| 17 |
-
dataset = None
|
| 18 |
-
faiss_index = None
|
| 19 |
-
normalized_data = None
|
| 20 |
-
book_titles = None
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def is_valid_isbn(isbn):
|
| 24 |
-
pattern = r'^(?:(?:978|979)\d{10}|\d{9}[0-9X])$'
|
| 25 |
-
return bool(re.match(pattern, isbn))
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def load_data(ratings_path, books_path) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
| 30 |
-
ratings = pd.read_csv(ratings_path, encoding='cp1251', sep=';', on_bad_lines='skip')
|
| 31 |
-
ratings = ratings[ratings['Book-Rating'] != 0]
|
| 32 |
-
|
| 33 |
-
books = pd.read_csv(books_path, encoding='cp1251', sep=';', on_bad_lines='skip')
|
| 34 |
-
|
| 35 |
-
return ratings, books
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def preprocess_data(ratings: pd.DataFrame, books: pd.DataFrame) -> pd.DataFrame:
|
| 39 |
-
dataset = pd.merge(ratings, books, on=['ISBN'])
|
| 40 |
-
return dataset.apply(lambda x: x.str.lower() if x.dtype == 'object' else x)
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def create_embedding(dataset):
|
| 44 |
-
model_name = "mrm8488/bert-tiny-finetuned-sms-spam-detection"
|
| 45 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 46 |
-
model = AutoModel.from_pretrained(model_name)
|
| 47 |
-
print("creating tokens")
|
| 48 |
-
tokens = [tokenizer(i, padding="max_length", truncation=True, max_length=10, return_tensors='pt')
|
| 49 |
-
for i in dataset]
|
| 50 |
-
print("\ncreating embedding\n")
|
| 51 |
-
emb = []
|
| 52 |
-
for i in tqdm(tokens):
|
| 53 |
-
emb.append(model(**i,)["last_hidden_state"].detach().numpy().squeeze().reshape(-1))
|
| 54 |
-
# Normalize the data
|
| 55 |
-
normalized_data = emb / np.linalg.norm(emb)
|
| 56 |
-
return normalized_data
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def build_faiss_index(dataset: pd.DataFrame) -> Tuple[faiss.IndexFlatIP, np.ndarray]:
|
| 60 |
-
if os.path.exists("books.index"):
|
| 61 |
-
return read_index("books.index")
|
| 62 |
-
|
| 63 |
-
dataset["embedding"] = create_embedding(dataset["Book-Title"])
|
| 64 |
-
print("creating index")
|
| 65 |
-
normalized_data = dataset["embedding"]
|
| 66 |
-
# Create a Faiss index
|
| 67 |
-
dimension = normalized_data.shape[-1]
|
| 68 |
-
index = faiss.IndexFlatIP(dimension)
|
| 69 |
-
|
| 70 |
-
# Add vectors to the index
|
| 71 |
-
index.add(normalized_data.astype('float16'))
|
| 72 |
-
|
| 73 |
-
write_index(index, "data/books.index")
|
| 74 |
-
|
| 75 |
-
return index
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def compute_correlations_faiss(index: faiss.IndexFlatIP, book_titles: List[str],
|
| 79 |
-
target_book, ) -> pd.DataFrame:
|
| 80 |
-
print(target_book, type(target_book))
|
| 81 |
-
emb = create_embedding([target_book[0]])
|
| 82 |
-
# target_vector = book_titles.index(emb)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
# Perform the search
|
| 86 |
-
k = len(book_titles) # Search for all books
|
| 87 |
-
similarities, I = index.search(emb.astype('float16'), k)
|
| 88 |
-
|
| 89 |
-
# # Reduce database and query vectors to 2D for visualization
|
| 90 |
-
# pca = PCA(n_components=2)
|
| 91 |
-
# reduced_db = pca.fit_transform(data)
|
| 92 |
-
# reduced_query = pca.transform(target_vector)
|
| 93 |
-
#
|
| 94 |
-
# # Scatter plot
|
| 95 |
-
# plt.scatter(reduced_db[:, 0], reduced_db[:, 1], label='Database Vectors', alpha=0.5)
|
| 96 |
-
# plt.scatter(reduced_query[:, 0], reduced_query[:, 1], label='Query Vectors', marker='X', color='red')
|
| 97 |
-
# plt.legend()
|
| 98 |
-
# plt.title("PCA Projection of IndexFlatIP Vectors")
|
| 99 |
-
# plt.show()
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
corr_df = pd.DataFrame({
|
| 104 |
-
'book': [book_titles[i] for i in I[0]],
|
| 105 |
-
'corr': similarities[0]
|
| 106 |
-
})
|
| 107 |
-
return corr_df.sort_values('corr', ascending=False)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
def load_and_prepare_data():
|
| 112 |
-
global dataset, faiss_index, normalized_data, book_titles, ratings_by_isbn
|
| 113 |
-
|
| 114 |
-
# Download data files from Hugging Face
|
| 115 |
-
ratings = "BX-Book-Ratings.csv"
|
| 116 |
-
books = "BX-Books.csv"
|
| 117 |
-
ratings, books = load_data(ratings, books)
|
| 118 |
-
dataset = preprocess_data(ratings, books)
|
| 119 |
-
ratings = ratings[ratings['ISBN'].apply(is_valid_isbn)]
|
| 120 |
-
dataset = dataset[dataset['ISBN'].apply(is_valid_isbn)]
|
| 121 |
-
|
| 122 |
-
ratings_by_isbn = ratings.drop(columns="User-ID")[ratings.drop(columns="User-ID")["Book-Rating"] > 0]
|
| 123 |
-
ratings_by_isbn = ratings_by_isbn.groupby('ISBN')["Book-Rating"].mean().reset_index()
|
| 124 |
-
ratings_by_isbn = ratings_by_isbn.drop_duplicates(subset=['ISBN'])
|
| 125 |
-
dataset = dataset.drop(columns=["User-ID", "Book-Rating"])
|
| 126 |
-
dataset = dataset[dataset['ISBN'].isin(ratings_by_isbn['ISBN'])]
|
| 127 |
-
dataset = dataset.drop_duplicates(subset=['ISBN'])
|
| 128 |
-
dataset = preprocess_data(dataset, ratings_by_isbn)
|
| 129 |
-
# Build Faiss index
|
| 130 |
-
faiss_index = build_faiss_index(dataset)
|
| 131 |
-
|
| 132 |
-
book_titles = dataset["Book-Title"]
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def recommend_books(target_book: str
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
"Title": dataset.loc[dataset['Book-Title'] == row['book'], 'Book-Title'].values[0],
|
| 167 |
-
"Author": dataset.loc[dataset['Book-Title'] == row['book'], 'Book-Author'].values[0],
|
| 168 |
-
"Year": dataset.loc[dataset['Book-Title'] == row['book'], 'Year-Of-Publication'].values[0],
|
| 169 |
-
"Publisher": dataset.loc[dataset['Book-Title'] == row['book'], 'Publisher'].values[0],
|
| 170 |
-
"ISBN": dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0],
|
| 171 |
-
"Rating": ratings_by_isbn.loc[
|
| 172 |
-
ratings_by_isbn['ISBN'] == dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[
|
| 173 |
-
0], 'Book-Rating'].values[0],
|
| 174 |
-
"none": dups.append(dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0])
|
| 175 |
-
}
|
| 176 |
-
for idx, (_, row) in enumerate(recommendations.iterrows(), 1)
|
| 177 |
-
if dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0] not in dups
|
| 178 |
-
])
|
| 179 |
-
|
| 180 |
-
return result_df
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
# Create Gradio interface
|
| 184 |
-
iface = gr.Interface(
|
| 185 |
-
fn=recommend_books,
|
| 186 |
-
inputs=[
|
| 187 |
-
gr.Textbox(label="Enter a book title"),
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# Launch the app
|
| 202 |
iface.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from typing import List, Tuple
|
| 8 |
+
import faiss
|
| 9 |
+
from faiss import write_index, read_index
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from fuzzywuzzy import process
|
| 12 |
+
from pandas import DataFrame
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from transformers import BertTokenizerFast, BertModel, AutoTokenizer, AutoModel
|
| 15 |
+
|
| 16 |
+
# Global variables to store loaded data
|
| 17 |
+
dataset = None
|
| 18 |
+
faiss_index = None
|
| 19 |
+
normalized_data = None
|
| 20 |
+
book_titles = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def is_valid_isbn(isbn):
|
| 24 |
+
pattern = r'^(?:(?:978|979)\d{10}|\d{9}[0-9X])$'
|
| 25 |
+
return bool(re.match(pattern, isbn))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_data(ratings_path, books_path) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
| 30 |
+
ratings = pd.read_csv(ratings_path, encoding='cp1251', sep=';', on_bad_lines='skip')
|
| 31 |
+
ratings = ratings[ratings['Book-Rating'] != 0]
|
| 32 |
+
|
| 33 |
+
books = pd.read_csv(books_path, encoding='cp1251', sep=';', on_bad_lines='skip')
|
| 34 |
+
|
| 35 |
+
return ratings, books
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def preprocess_data(ratings: pd.DataFrame, books: pd.DataFrame) -> pd.DataFrame:
|
| 39 |
+
dataset = pd.merge(ratings, books, on=['ISBN'])
|
| 40 |
+
return dataset.apply(lambda x: x.str.lower() if x.dtype == 'object' else x)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def create_embedding(dataset):
|
| 44 |
+
model_name = "mrm8488/bert-tiny-finetuned-sms-spam-detection"
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 46 |
+
model = AutoModel.from_pretrained(model_name)
|
| 47 |
+
print("creating tokens")
|
| 48 |
+
tokens = [tokenizer(i, padding="max_length", truncation=True, max_length=10, return_tensors='pt')
|
| 49 |
+
for i in dataset]
|
| 50 |
+
print("\ncreating embedding\n")
|
| 51 |
+
emb = []
|
| 52 |
+
for i in tqdm(tokens):
|
| 53 |
+
emb.append(model(**i,)["last_hidden_state"].detach().numpy().squeeze().reshape(-1))
|
| 54 |
+
# Normalize the data
|
| 55 |
+
normalized_data = emb / np.linalg.norm(emb)
|
| 56 |
+
return normalized_data
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def build_faiss_index(dataset: pd.DataFrame) -> Tuple[faiss.IndexFlatIP, np.ndarray]:
|
| 60 |
+
if os.path.exists("books.index"):
|
| 61 |
+
return read_index("books.index")
|
| 62 |
+
|
| 63 |
+
dataset["embedding"] = create_embedding(dataset["Book-Title"])
|
| 64 |
+
print("creating index")
|
| 65 |
+
normalized_data = dataset["embedding"]
|
| 66 |
+
# Create a Faiss index
|
| 67 |
+
dimension = normalized_data.shape[-1]
|
| 68 |
+
index = faiss.IndexFlatIP(dimension)
|
| 69 |
+
|
| 70 |
+
# Add vectors to the index
|
| 71 |
+
index.add(normalized_data.astype('float16'))
|
| 72 |
+
|
| 73 |
+
write_index(index, "data/books.index")
|
| 74 |
+
|
| 75 |
+
return index
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def compute_correlations_faiss(index: faiss.IndexFlatIP, book_titles: List[str],
|
| 79 |
+
target_book, ) -> pd.DataFrame:
|
| 80 |
+
print(target_book, type(target_book))
|
| 81 |
+
emb = create_embedding([target_book[0]])
|
| 82 |
+
# target_vector = book_titles.index(emb)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# Perform the search
|
| 86 |
+
k = len(book_titles) # Search for all books
|
| 87 |
+
similarities, I = index.search(emb.astype('float16'), k)
|
| 88 |
+
|
| 89 |
+
# # Reduce database and query vectors to 2D for visualization
|
| 90 |
+
# pca = PCA(n_components=2)
|
| 91 |
+
# reduced_db = pca.fit_transform(data)
|
| 92 |
+
# reduced_query = pca.transform(target_vector)
|
| 93 |
+
#
|
| 94 |
+
# # Scatter plot
|
| 95 |
+
# plt.scatter(reduced_db[:, 0], reduced_db[:, 1], label='Database Vectors', alpha=0.5)
|
| 96 |
+
# plt.scatter(reduced_query[:, 0], reduced_query[:, 1], label='Query Vectors', marker='X', color='red')
|
| 97 |
+
# plt.legend()
|
| 98 |
+
# plt.title("PCA Projection of IndexFlatIP Vectors")
|
| 99 |
+
# plt.show()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
corr_df = pd.DataFrame({
|
| 104 |
+
'book': [book_titles[i] for i in I[0]],
|
| 105 |
+
'corr': similarities[0]
|
| 106 |
+
})
|
| 107 |
+
return corr_df.sort_values('corr', ascending=False)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def load_and_prepare_data():
|
| 112 |
+
global dataset, faiss_index, normalized_data, book_titles, ratings_by_isbn
|
| 113 |
+
|
| 114 |
+
# Download data files from Hugging Face
|
| 115 |
+
ratings = "BX-Book-Ratings.csv"
|
| 116 |
+
books = "BX-Books.csv"
|
| 117 |
+
ratings, books = load_data(ratings, books)
|
| 118 |
+
dataset = preprocess_data(ratings, books)
|
| 119 |
+
ratings = ratings[ratings['ISBN'].apply(is_valid_isbn)]
|
| 120 |
+
dataset = dataset[dataset['ISBN'].apply(is_valid_isbn)]
|
| 121 |
+
|
| 122 |
+
ratings_by_isbn = ratings.drop(columns="User-ID")[ratings.drop(columns="User-ID")["Book-Rating"] > 0]
|
| 123 |
+
ratings_by_isbn = ratings_by_isbn.groupby('ISBN')["Book-Rating"].mean().reset_index()
|
| 124 |
+
ratings_by_isbn = ratings_by_isbn.drop_duplicates(subset=['ISBN'])
|
| 125 |
+
dataset = dataset.drop(columns=["User-ID", "Book-Rating"])
|
| 126 |
+
dataset = dataset[dataset['ISBN'].isin(ratings_by_isbn['ISBN'])]
|
| 127 |
+
dataset = dataset.drop_duplicates(subset=['ISBN'])
|
| 128 |
+
dataset = preprocess_data(dataset, ratings_by_isbn)
|
| 129 |
+
# Build Faiss index
|
| 130 |
+
faiss_index = build_faiss_index(dataset)
|
| 131 |
+
|
| 132 |
+
book_titles = dataset["Book-Title"]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def recommend_books(target_book: str):
|
| 136 |
+
num_recommendations: int = 15
|
| 137 |
+
global dataset, faiss_index, normalized_data, book_titles, ratings_by_isbn
|
| 138 |
+
|
| 139 |
+
if dataset is None or faiss_index is None or normalized_data is None or book_titles is None:
|
| 140 |
+
load_and_prepare_data()
|
| 141 |
+
dataset['ISBN'] = dataset['ISBN'].str.strip()
|
| 142 |
+
print("Before dropping duplicates:", len(dataset))
|
| 143 |
+
dataset = dataset.drop_duplicates(subset=['ISBN'])
|
| 144 |
+
print("After dropping duplicates:", len(dataset))
|
| 145 |
+
|
| 146 |
+
target_book = target_book.lower()
|
| 147 |
+
# Fuzzy match the input to the closest book title
|
| 148 |
+
closest_match = process.extractOne(target_book, book_titles)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
correlations = compute_correlations_faiss(faiss_index, book_titles, closest_match)
|
| 152 |
+
|
| 153 |
+
recommendations = correlations[correlations['book'] != target_book]
|
| 154 |
+
|
| 155 |
+
# Create a mask of unique ISBNs
|
| 156 |
+
unique_mask = dataset.duplicated(subset=['ISBN'], keep='first') == False
|
| 157 |
+
|
| 158 |
+
# Apply the mask
|
| 159 |
+
dataset = dataset[unique_mask]
|
| 160 |
+
|
| 161 |
+
recommendations = recommendations.head(num_recommendations)
|
| 162 |
+
|
| 163 |
+
dups = []
|
| 164 |
+
result_df = pd.DataFrame([
|
| 165 |
+
{
|
| 166 |
+
"Title": dataset.loc[dataset['Book-Title'] == row['book'], 'Book-Title'].values[0],
|
| 167 |
+
"Author": dataset.loc[dataset['Book-Title'] == row['book'], 'Book-Author'].values[0],
|
| 168 |
+
"Year": dataset.loc[dataset['Book-Title'] == row['book'], 'Year-Of-Publication'].values[0],
|
| 169 |
+
"Publisher": dataset.loc[dataset['Book-Title'] == row['book'], 'Publisher'].values[0],
|
| 170 |
+
"ISBN": dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0],
|
| 171 |
+
"Rating": ratings_by_isbn.loc[
|
| 172 |
+
ratings_by_isbn['ISBN'] == dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[
|
| 173 |
+
0], 'Book-Rating'].values[0],
|
| 174 |
+
"none": dups.append(dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0])
|
| 175 |
+
}
|
| 176 |
+
for idx, (_, row) in enumerate(recommendations.iterrows(), 1)
|
| 177 |
+
if dataset.loc[dataset['Book-Title'] == row['book'], 'ISBN'].values[0] not in dups
|
| 178 |
+
])
|
| 179 |
+
|
| 180 |
+
return result_df
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Create Gradio interface
|
| 184 |
+
iface = gr.Interface(
|
| 185 |
+
fn=recommend_books,
|
| 186 |
+
inputs=[
|
| 187 |
+
gr.Textbox(label="Enter a book title"),
|
| 188 |
+
],
|
| 189 |
+
outputs=[
|
| 190 |
+
gr.Dataframe(
|
| 191 |
+
headers=["Title", "Author", "Year", "Publisher", "ISBN", "Rating"],
|
| 192 |
+
type="pandas",
|
| 193 |
+
|
| 194 |
+
)
|
| 195 |
+
],
|
| 196 |
+
title="Book Recommender",
|
| 197 |
+
description="Enter a book title to get recommendations based on user ratings and book similarities."
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Launch the app
|
|
|
|
| 201 |
iface.launch()
|