Spaces:
Sleeping
Sleeping
File size: 7,582 Bytes
26540ec d677582 26540ec 4a60c2e 26540ec f20e1de 26540ec d677582 26540ec f20e1de 26540ec d677582 26540ec d677582 26540ec f20e1de 26540ec d677582 26540ec d677582 26540ec |
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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
from pandas import read_pickle
import streamlit as st
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from streamlit_extras.add_vertical_space import add_vertical_space
from streamlit_extras.colored_header import colored_header
from streamlit_option_menu import option_menu
max_seq_length = 256
repo_id = "all-MiniLM-L6-v2"
data_path = "detailed_movies_top_250_embeds.pkl.xz"
output_column_names = [
"year",
"duration",
"genre",
"stars",
"summary",
"poster_url",
"trailer_url",
]
vertical_space = 2
st.set_page_config(layout="wide")
colored_header(
label="SEARCH ENGINE&MOVIE RECOMMENDER: IMDB TOP 250 MOVIES",
description="""Discover the best movies from the IMDB Top 250 list with advanced semantic search engine and movie recommender.
Simply enter a keyword, phrase, or even plot.
It provides you with a personalized selection of top-rated films!""",
color_name="blue-70",
)
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
@st.cache(suppress_st_warning=True, allow_output_mutation=True)
def load_data_model():
"""
It loads the dataframe and the sentence embedding model.
Returns:
A tuple of the dataframe and the embedding model
"""
df = read_pickle(data_path)
embed_model = SentenceTransformer(repo_id)
embed_model.max_seq_length = max_seq_length
return df, embed_model
def top_n_retriever(titles, similarity_scores, n, query_type):
"""
It takes in a list of titles, a numpy array of similarity scores, the number of results to return,
and the type of query (search engine or similar movies). It then returns the top n results
Args:
titles (list[str]): List of movie titles
similarity_scores (ndarray): The cosine similarity scores of the query movie with all the movies
in the dataset.
n (int): The number of results to return
query_type (str): This is the type of query. It can be either "Search Engine" or "Similar Movies".
Returns:
The top n movies that are similar to the query movie.
"""
sim_scores = zip(titles, similarity_scores)
sorted_sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
if query_type == "Search Engine":
sorted_sim_scores = sorted_sim_scores[:n]
if query_type == "Similar Movies":
sorted_sim_scores = sorted_sim_scores[1 : n + 1]
return [i[0] for i in sorted_sim_scores]
def grid_maker(movie_recs, df):
"""
It takes the list of recommended movies and the dataframe as input and outputs a grid of movie
posters and details
Args:
movie_recs (List[str]): - a list of movie titles
df (object): the dataframe containing the movie data
"""
for movie in movie_recs:
poster_col, title_col = st.columns([1, 8])
(year, duration, genre, stars, summary, poster_url, trailer_url) = (
df[output_column_names][df.title == movie]
).values.flatten()
poster_col.image(poster_url)
poster_col.markdown(
f'<a href={trailer_url}><button style="background-color:GreenYellow;">🎥Trailer</button></a>',
unsafe_allow_html=True,
)
title_col.markdown(f"""<p>
<span style=color:#0068C9;font-style:bold;font-size:28px;>{movie} </span>
<span style=color:grey;font-style:italic;font-size:14px;> {year} | {duration} | {genre}</span>
<span style="background-color:rgba(0, 0, 0, 0.1);"><br>{stars}</span>
<span style="word-wrap:break-word;font-family:roboto;font-weight: 700;">
<br>{summary}</span>
</p>
""", unsafe_allow_html=True)
add_vertical_space(vertical_space)
def filter_df(df, selected_page):
"""
The function takes in a dataframe, and the selected page, and returns the selected movie, the
filtered dataframe, and the top_n number of recommendations
Args:
df (object): the dataframe
selected_page (str): the page that the user is on
Returns:
selected_movie, filtered_df, top_n
"""
filtered_df = df.copy()
text_input, genre_box, top_n_rec = st.columns([3, 1, 2])
with genre_box:
selected_genre = st.selectbox("Genre", genres_list)
with top_n_rec:
top_n = st.slider("Number of Recommendations", 1, 15, 5)
if selected_genre != "All":
filtered_df = df[df.genre.str.contains(selected_genre)]
if selected_page == "Similar Movies":
with text_input:
selected_movie = st.selectbox("Movie", movie_list)
return selected_movie, filtered_df, top_n
if selected_page == "Search Engine":
with text_input:
query = st.text_input("Query", value="Mafia")
return query, filtered_df, top_n
def get_results_button():
"""
It creates a button that says "Get Results ◀" and returns it
Returns:
A button object.
"""
_, _, col_center, _, _ = st.columns(5)
return col_center.button("Get Results ◀")
df, embed_model = load_data_model()
df["trailer_url"] = df["trailer_url"].astype(str)
movie_list = df["title"].values
genres_list = list(set(df["genre"].str.split(", ").sum()))
genres_list.insert(0, "All")
selected_page = option_menu(
menu_title=None, # required
options=["Search Engine", "Similar Movies"], # required
icons=["search", "film"], # optional
menu_icon="cast", # optional
default_index=0, # optional
orientation="horizontal",
styles={
"container": {"padding": "0!important", "background-color": "#fafafa"},
"icon": {"color": "orange", "font-size": "25px"},
"nav-link": {
"font-size": "25px",
"text-align": "left",
"margin": "0px",
"--hover-color": "#eee",
},
"nav-link-selected": {"background-color": "#0068C9"},
},
)
if selected_page == "Search Engine":
query, genre_df, top_n = filter_df(df, selected_page)
query_embed = embed_model.encode(query)
bt = get_results_button()
if bt:
if query == "":
st.warning("You should type something", icon="⚠️")
else:
semantic_sims = [
cosine_similarity([query_embed], [movie_embed]).item()
for movie_embed in genre_df.embedding
]
movie_recs = top_n_retriever(
genre_df.title, semantic_sims, top_n, selected_page
)
add_vertical_space(vertical_space)
grid_maker(movie_recs, genre_df)
if selected_page == "Similar Movies":
st.info("Movies are recommended based on plot similarity!")
selected_movie, genre_df, top_n = filter_df(df, selected_page)
bt = get_results_button()
if bt:
movie_sims = [
cosine_similarity(
list(df.embedding[df.title == selected_movie]), [movie_embed]
).item()
for movie_embed in genre_df.embedding
]
movie_recs = top_n_retriever(genre_df.title, movie_sims, top_n, selected_page)
add_vertical_space(vertical_space)
grid_maker(movie_recs, genre_df)
|