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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from surprise import Reader, Dataset, SVD
|
| 7 |
+
from surprise.model_selection import cross_validate
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_model():
|
| 14 |
+
if torch.cuda.is_available():
|
| 15 |
+
device = "cuda"
|
| 16 |
+
else:
|
| 17 |
+
device = "cpu"
|
| 18 |
+
|
| 19 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2").to(device)
|
| 20 |
+
return model
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def encode_and_calculate_similarity(model):
|
| 24 |
+
sentence_embeddings = model.encode(df_merged["soup"].tolist())
|
| 25 |
+
|
| 26 |
+
cos_sim = cosine_similarity(sentence_embeddings)
|
| 27 |
+
|
| 28 |
+
return cos_sim
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def svd():
|
| 32 |
+
reader = Reader()
|
| 33 |
+
data = Dataset.load_from_df(df_ratings[["userId", "movieId", "rating"]], reader)
|
| 34 |
+
svd = SVD()
|
| 35 |
+
cross_validate(svd, data, measures=["RMSE", "MAE"], cv=5, verbose=True)
|
| 36 |
+
|
| 37 |
+
trainset = data.build_full_trainset()
|
| 38 |
+
svd.fit(trainset)
|
| 39 |
+
return svd
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_sorted_movie_indices(title: str, cos_sim: np.ndarray) -> list[int]:
|
| 43 |
+
"""
|
| 44 |
+
Retrieve the sorted indices of movies based on their similarity scores to a given movie.
|
| 45 |
+
|
| 46 |
+
:param title: The title of the movie to find similar movies for.
|
| 47 |
+
:param cos_sim: The cosine similarity matrix of movies.
|
| 48 |
+
:return: A list of sorted movie indices.
|
| 49 |
+
"""
|
| 50 |
+
try:
|
| 51 |
+
# Get the index of the movie that matches the title
|
| 52 |
+
movie_index = movie_indices[title.lower()]
|
| 53 |
+
|
| 54 |
+
# If there are multiple movies with the same title, pick the first one.
|
| 55 |
+
if isinstance(movie_index, pd.Series):
|
| 56 |
+
movie_index = movie_index[0]
|
| 57 |
+
|
| 58 |
+
except KeyError:
|
| 59 |
+
print(f"Movie '{title}' not found. Please enter a valid movie title.")
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
# Get the pairwise similarity scores of all movies with that movie
|
| 63 |
+
sim_scores = list(enumerate(cos_sim[movie_index]))
|
| 64 |
+
|
| 65 |
+
# Sort the movies based on the similarity scores
|
| 66 |
+
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)[1:]
|
| 67 |
+
|
| 68 |
+
# Get the movie indices
|
| 69 |
+
sorted_movie_indices = [sim_score[0] for sim_score in sim_scores]
|
| 70 |
+
|
| 71 |
+
return sorted_movie_indices
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_qualified_movies(
|
| 75 |
+
df: pd.DataFrame, df_qualified: pd.DataFrame, sorted_movie_indices: list[int]
|
| 76 |
+
) -> pd.DataFrame:
|
| 77 |
+
"""
|
| 78 |
+
Filter out movies that are not in the qualified movies chart based on IMDB's weighted rating.
|
| 79 |
+
|
| 80 |
+
:param df: The DataFrame containing movie details.
|
| 81 |
+
:param df_qualified: The DataFrame containing qualified movie details.
|
| 82 |
+
:param sorted_movie_indices: A list of movie indices sorted by similarity scores.
|
| 83 |
+
:return: A Pandas DataFrame containing the qualified movies sorted by similarity scores.
|
| 84 |
+
"""
|
| 85 |
+
movie_details = [
|
| 86 |
+
"id",
|
| 87 |
+
"title",
|
| 88 |
+
"genres",
|
| 89 |
+
"original_language",
|
| 90 |
+
"production_countries",
|
| 91 |
+
"release_date",
|
| 92 |
+
"runtime",
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
sorted_movies = df.loc[sorted_movie_indices, movie_details]
|
| 96 |
+
qualified_movies = sorted_movies[sorted_movies["id"].isin(df_qualified["id"])]
|
| 97 |
+
return qualified_movies
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def predict_user_rating(
|
| 101 |
+
userId: int, qualified_movies: pd.DataFrame, indices_map: pd.DataFrame
|
| 102 |
+
) -> pd.DataFrame:
|
| 103 |
+
"""
|
| 104 |
+
Predict the user rating for qualified movies using SVD and return the sorted DataFrame.
|
| 105 |
+
|
| 106 |
+
:param userId: The ID of the user.
|
| 107 |
+
:param qualified_movies: A Pandas DataFrame containing qualified movies data.
|
| 108 |
+
:return: A Pandas DataFrame containing the final qualified movies sorted by estimated user ratings.
|
| 109 |
+
"""
|
| 110 |
+
# Calculate estimated user ratings for qualified movies using SVD
|
| 111 |
+
qualified_movies["predicted_user_rating"] = qualified_movies["id"].apply(
|
| 112 |
+
lambda x: round(svd.predict(userId, indices_map.loc[x]["movieId"]).est, 2)
|
| 113 |
+
)
|
| 114 |
+
final_qualified_movies = qualified_movies.sort_values(
|
| 115 |
+
by=["predicted_user_rating"], ascending=False
|
| 116 |
+
)
|
| 117 |
+
return final_qualified_movies
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def get_movie_recommendations_hybrid(title: str, userId: int) -> pd.DataFrame:
|
| 121 |
+
"""
|
| 122 |
+
Get movie recommendations based on a given title and user ID.
|
| 123 |
+
|
| 124 |
+
:param title: The title of the movie to find similar movies for.
|
| 125 |
+
:param userId: The ID of the user.
|
| 126 |
+
:return: A Pandas DataFrame containing the recommended movies
|
| 127 |
+
"""
|
| 128 |
+
# Get recommended movie indices based on the given title
|
| 129 |
+
sorted_movie_indices = get_sorted_movie_indices(title, cos_sim)
|
| 130 |
+
|
| 131 |
+
# Filter out bad movies and select the top 50 qualified movies
|
| 132 |
+
qualified_movies = get_qualified_movies(
|
| 133 |
+
df_merged, df_qualified, sorted_movie_indices
|
| 134 |
+
).head(50)
|
| 135 |
+
|
| 136 |
+
# Predict user ratings for qualified movies and select the top recommended movies
|
| 137 |
+
recommended_movies = predict_user_rating(
|
| 138 |
+
userId, qualified_movies, indices_map
|
| 139 |
+
).head(5)
|
| 140 |
+
|
| 141 |
+
recommended_movies.columns = [
|
| 142 |
+
"ID",
|
| 143 |
+
"Title",
|
| 144 |
+
"Genres",
|
| 145 |
+
"Language",
|
| 146 |
+
"Production Countries",
|
| 147 |
+
"Release Date",
|
| 148 |
+
"Runtime",
|
| 149 |
+
"Predicted User Rating",
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
return recommended_movies
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
df_qualified = pd.read_csv("data/qualified_movies.csv")
|
| 157 |
+
df_ratings = pd.read_csv("data/ratings_small.csv")
|
| 158 |
+
df_merged = pd.read_csv("data/df_merged.csv")
|
| 159 |
+
|
| 160 |
+
model = load_model()
|
| 161 |
+
cos_sim = encode_and_calculate_similarity(model)
|
| 162 |
+
movie_indices = pd.Series(
|
| 163 |
+
df_merged.index, index=df_merged["title"].apply(lambda title: title.lower())
|
| 164 |
+
).drop_duplicates()
|
| 165 |
+
|
| 166 |
+
svd = svd()
|
| 167 |
+
indices_map = df_merged.set_index("id")
|
| 168 |
+
|
| 169 |
+
with gr.Blocks(theme=gr.themes.Soft(text_size="lg")) as demo:
|
| 170 |
+
gr.Markdown(
|
| 171 |
+
"""
|
| 172 |
+
# Movie Recommendation System
|
| 173 |
+
"""
|
| 174 |
+
)
|
| 175 |
+
title = gr.Dropdown(
|
| 176 |
+
choices=df_merged["title"].unique().tolist(),
|
| 177 |
+
label="Movie Title",
|
| 178 |
+
value="Iron Man",
|
| 179 |
+
)
|
| 180 |
+
user_id = gr.Number(
|
| 181 |
+
value=1, label="User ID", info="Please enter a number between 1 and 671!"
|
| 182 |
+
)
|
| 183 |
+
recommend_button = gr.Button("Get Movie Recommendations")
|
| 184 |
+
recommended_movies = gr.DataFrame(label="Movie Recommendations")
|
| 185 |
+
recommend_button.click(
|
| 186 |
+
get_movie_recommendations_hybrid,
|
| 187 |
+
inputs=[title, user_id],
|
| 188 |
+
outputs=recommended_movies,
|
| 189 |
+
)
|
| 190 |
+
examples = gr.Examples(
|
| 191 |
+
examples=[
|
| 192 |
+
"Captain America: The First Avenger",
|
| 193 |
+
"The Conjuring",
|
| 194 |
+
"Toy Story",
|
| 195 |
+
"Final Destination 5",
|
| 196 |
+
],
|
| 197 |
+
inputs=[title],
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
demo.launch()
|