-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
342 lines (321 loc) · 11.5 KB
/
app.py
File metadata and controls
342 lines (321 loc) · 11.5 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#
#
# import pickle
# import streamlit as st
# import requests
#
# # TMDB API Key
# API_KEY = "cb75e7c6aad1a1f40d91822a76a147e8"
#
# # Load data
# movies = pickle.load(open('movies.pkl', 'rb'))
# similarity = pickle.load(open('similarity.pkl', 'rb'))
#
# # Fetch poster
# def fetch_poster(movie_id):
# url = f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={API_KEY}&language=en-US"
# data = requests.get(url).json()
# poster_path = data.get('poster_path')
# return f"https://image.tmdb.org/t/p/w500/{poster_path}" if poster_path else ""
#
# # Fetch detailed info
# def fetch_movie_details(movie_id):
# url = f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={API_KEY}&language=en-US&append_to_response=videos,credits"
# return requests.get(url).json()
#
# # Recommend logic
# def recommend(movie):
# index = movies[movies['title'] == movie].index[0]
# distances = sorted(enumerate(similarity[index]), reverse=True, key=lambda x: x[1])
# names, posters, ids = [], [], []
# for i in distances[1:6]:
# movie_id = movies.iloc[i[0]].movie_id
# ids.append(movie_id)
# posters.append(fetch_poster(movie_id))
# names.append(movies.iloc[i[0]].title)
# return names, posters, ids
#
# # Streamlit Config
# st.set_page_config(page_title="Movie Recommender", layout="wide")
#
# # CSS Styling
# st.markdown("""
# <style>
# body {
# background-color: #1e1e1e;
# }
# h1 {
# color: #0ef;
# text-align: center;
# font-size: 3rem;
# font-weight: 900;
# }
# .poster-container {
# border-radius: 15px;
# overflow: hidden;
# box-shadow: 0 0 10px rgba(0, 238, 255, 0.3);
# cursor: default;
# text-align: center;
# margin-bottom: 10px;
# }
# .poster-container:hover {
# transform: scale(1.05);
# box-shadow: 0 0 20px rgba(0, 238, 255, 0.6);
# }
# .poster-img {
# width: 100%;
# height: 300px;
# object-fit: cover;
# border-radius: 15px;
# }
# .movie-title {
# color: white;
# font-size: 1rem;
# margin-top: 8px;
# font-weight: bold;
# }
# .stButton>button {
# background-color: #0ef;
# color: black;
# font-weight: bold;
# border: none;
# padding: 0.5em 1em;
# border-radius: 10px;
# box-shadow: 0 0 10px rgba(0, 238, 255, 0.6);
# }
# .stButton>button:hover {
# transform: scale(1.05);
# box-shadow: 0 0 20px rgba(0, 238, 255, 1);
# }
# .details-box {
# background-color: #111;
# border-radius: 15px;
# padding: 20px;
# color: white;
# box-shadow: 0 0 15px rgba(0, 238, 255, 0.3);
# }
# </style>
# """, unsafe_allow_html=True)
#
# # App Title
# st.markdown("<h1>🎬 Minimalist Movie Recommender</h1>", unsafe_allow_html=True)
#
# # Session state
# if 'clicked_movie_id' not in st.session_state:
# st.session_state.clicked_movie_id = None
# if 'recommendations' not in st.session_state:
# st.session_state.recommendations = None
#
# # Selectbox
# selected_movie = st.selectbox("🔍 Choose a movie you like", movies['title'].values)
#
# # Button to show recommendations
# if st.button("🎥 Show Recommendations"):
# st.session_state.clicked_movie_id = None
# st.session_state.recommendations = recommend(selected_movie)
#
# # Show recommended posters
# if st.session_state.recommendations and not st.session_state.clicked_movie_id:
# names, posters, ids = st.session_state.recommendations
# st.markdown("### Recommended for You:")
# cols = st.columns(5)
# for i in range(5):
# with cols[i]:
# st.markdown(f"""
# <div class="poster-container">
# <img src="{posters[i]}" class="poster-img" alt="{names[i]}" />
# <div class="movie-title">{names[i]}</div>
# </div>
# """, unsafe_allow_html=True)
# with st.form(key=f"form_{i}"):
# submitted = st.form_submit_button("ℹ️ More Info", use_container_width=True)
# if submitted:
# st.session_state.clicked_movie_id = ids[i]
# st.rerun()
#
# # Show movie detail
# if st.session_state.clicked_movie_id:
# details = fetch_movie_details(st.session_state.clicked_movie_id)
# st.markdown("---")
# st.markdown(f"<div class='details-box'>", unsafe_allow_html=True)
# st.markdown(f"## 🎥 {details.get('title')} ({details.get('release_date', '')[:4]})")
# cols = st.columns([1, 2])
# with cols[0]:
# st.image(fetch_poster(st.session_state.clicked_movie_id), width=300)
# with cols[1]:
# st.markdown(f"**📅 Release Date:** {details.get('release_date')}")
# st.markdown(f"**⭐ Rating:** {details.get('vote_average')} / 10")
# st.markdown(f"**🗣️ Language:** {details.get('original_language', '').upper()}")
# genres = ", ".join([g['name'] for g in details.get('genres', [])])
# st.markdown(f"**🎭 Genres:** {genres}")
# crew = details.get('credits', {}).get('crew', [])
# director = next((p['name'] for p in crew if p['job'] == 'Director'), 'N/A')
# st.markdown(f"**🎬 Director:** {director}")
# cast = details.get('credits', {}).get('cast', [])[:5]
# cast_names = ", ".join([actor['name'] for actor in cast])
# st.markdown(f"**🧑🤝🧑 Cast:** {cast_names}")
# st.markdown(f"**📝 Overview:** {details.get('overview')}")
# trailer = next((vid for vid in details.get('videos', {}).get('results', []) if vid['type'] == 'Trailer' and vid['site'] == 'YouTube'), None)
# if trailer:
# st.markdown(f"[▶️ Watch Trailer](https://www.youtube.com/watch?v={trailer['key']})")
# st.markdown("</div>", unsafe_allow_html=True)
#
# # Back button
# if st.button("🔙 Back to Recommendations"):
# st.session_state.clicked_movie_id = None
# st.rerun()
import os
import pickle
import streamlit as st
import requests
import gdown
# Google Drive links
MOVIES_URL = "https://drive.google.com/uc?id=1BT4c0seOYKsESyvLH6nJK1NxAc--EAd8"
SIMILARITY_URL = "https://drive.google.com/uc?id=1FzQeQAH1XpKQU2zQk0ZxplZygZJ6NA1d"
# Download if not present
if not os.path.exists("movies.pkl"):
gdown.download(MOVIES_URL, "movies.pkl", quiet=False)
if not os.path.exists("similarity.pkl"):
gdown.download(SIMILARITY_URL, "similarity.pkl", quiet=False)
# Load files
movies = pickle.load(open('movies.pkl', 'rb'))
similarity = pickle.load(open('similarity.pkl', 'rb'))
# TMDB API
API_KEY = "cb75e7c6aad1a1f40d91822a76a147e8"
def fetch_poster(movie_id):
url = f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={API_KEY}&language=en-US"
data = requests.get(url).json()
poster_path = data.get('poster_path')
return f"https://image.tmdb.org/t/p/w500/{poster_path}" if poster_path else ""
def fetch_movie_details(movie_id):
url = f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={API_KEY}&language=en-US&append_to_response=videos,credits"
return requests.get(url).json()
def recommend(movie):
index = movies[movies['title'] == movie].index[0]
distances = sorted(enumerate(similarity[index]), reverse=True, key=lambda x: x[1])
names, posters, ids = [], [], []
for i in distances[1:6]:
movie_id = movies.iloc[i[0]].movie_id
ids.append(movie_id)
posters.append(fetch_poster(movie_id))
names.append(movies.iloc[i[0]].title)
return names, posters, ids
# Streamlit UI
st.set_page_config(page_title="Movie Recommender", layout="wide")
# Styling
st.markdown("""
<style>
body {
background-color: #1e1e1e;
}
h1 {
color: #0ef;
text-align: center;
font-size: 3rem;
font-weight: 900;
}
.poster-container {
border-radius: 15px;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 238, 255, 0.3);
cursor: default;
text-align: center;
margin-bottom: 10px;
}
.poster-container:hover {
transform: scale(1.05);
box-shadow: 0 0 20px rgba(0, 238, 255, 0.6);
}
.poster-img {
width: 100%;
height: 300px;
object-fit: cover;
border-radius: 15px;
}
.movie-title {
color: white;
font-size: 1rem;
margin-top: 8px;
font-weight: bold;
}
.stButton>button {
background-color: #0ef;
color: black;
font-weight: bold;
border: none;
padding: 0.5em 1em;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 238, 255, 0.6);
}
.stButton>button:hover {
transform: scale(1.05);
box-shadow: 0 0 20px rgba(0, 238, 255, 1);
}
.details-box {
background-color: #111;
border-radius: 15px;
padding: 20px;
color: white;
box-shadow: 0 0 15px rgba(0, 238, 255, 0.3);
}
</style>
""", unsafe_allow_html=True)
# App Title
st.markdown("<h1>🎬 Minimalist Movie Recommender</h1>", unsafe_allow_html=True)
# Session
if 'clicked_movie_id' not in st.session_state:
st.session_state.clicked_movie_id = None
if 'recommendations' not in st.session_state:
st.session_state.recommendations = None
# Selectbox
selected_movie = st.selectbox("🔍 Choose a movie you like", movies['title'].values)
if st.button("🎥 Show Recommendations"):
st.session_state.clicked_movie_id = None
st.session_state.recommendations = recommend(selected_movie)
# Posters
if st.session_state.recommendations and not st.session_state.clicked_movie_id:
names, posters, ids = st.session_state.recommendations
st.markdown("### Recommended for You:")
cols = st.columns(5)
for i in range(5):
with cols[i]:
st.markdown(f"""
<div class="poster-container">
<img src="{posters[i]}" class="poster-img" alt="{names[i]}" />
<div class="movie-title">{names[i]}</div>
</div>
""", unsafe_allow_html=True)
with st.form(key=f"form_{i}"):
submitted = st.form_submit_button("ℹ️ More Info", use_container_width=True)
if submitted:
st.session_state.clicked_movie_id = ids[i]
st.rerun()
# Details
if st.session_state.clicked_movie_id:
details = fetch_movie_details(st.session_state.clicked_movie_id)
st.markdown("---")
st.markdown(f"<div class='details-box'>", unsafe_allow_html=True)
st.markdown(f"## 🎥 {details.get('title')} ({details.get('release_date', '')[:4]})")
cols = st.columns([1, 2])
with cols[0]:
st.image(fetch_poster(st.session_state.clicked_movie_id), width=300)
with cols[1]:
st.markdown(f"**📅 Release Date:** {details.get('release_date')}")
st.markdown(f"**⭐ Rating:** {details.get('vote_average')} / 10")
st.markdown(f"**🗣️ Language:** {details.get('original_language', '').upper()}")
genres = ", ".join([g['name'] for g in details.get('genres', [])])
st.markdown(f"**🎭 Genres:** {genres}")
crew = details.get('credits', {}).get('crew', [])
director = next((p['name'] for p in crew if p['job'] == 'Director'), 'N/A')
st.markdown(f"**🎬 Director:** {director}")
cast = details.get('credits', {}).get('cast', [])[:5]
cast_names = ", ".join([actor['name'] for actor in cast])
st.markdown(f"**🧑🤝🧑 Cast:** {cast_names}")
st.markdown(f"**📝 Overview:** {details.get('overview')}")
trailer = next((vid for vid in details.get('videos', {}).get('results', []) if vid['type'] == 'Trailer' and vid['site'] == 'YouTube'), None)
if trailer:
st.markdown(f"[▶️ Watch Trailer](https://www.youtube.com/watch?v={trailer['key']})")
st.markdown("</div>", unsafe_allow_html=True)
if st.button("🔙 Back to Recommendations"):
st.session_state.clicked_movie_id = None
st.rerun()