-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
280 lines (220 loc) · 9.86 KB
/
app.py
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
from db import get_db_connection
import requests, pickle, os
from flask import Flask, redirect, render_template, request, session, jsonify, flash
from flask_session import Session
from werkzeug.security import check_password_hash, generate_password_hash
from functools import wraps
from dotenv import load_dotenv
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['DEBUG'] = True
Session(app)
load_dotenv()
api_key = os.getenv("API_KEY")
connection = get_db_connection()
cursor = connection.cursor()
def fetch_poster(movie_id):
url = "https://api.themoviedb.org/3/movie/{}?api_key={}&language=en-US".format(movie_id, api_key)
data = requests.get(url)
data = data.json()
poster_path = data['poster_path']
full_path = "https://image.tmdb.org/t/p/w500/"+poster_path
return full_path
def combine_files(part_count, output_file):
combined_data = []
for i in range(1, part_count + 1):
part_file = f"data/similarity_part{i}.pkl"
with open(part_file, 'rb') as f:
combined_data.append(pickle.load(f))
# Retorne os dados combinados
return combined_data
# Caminho do arquivo combinado
output_file = "data/similarity_combined.pkl"
# Verifica se o arquivo combinado já existe
if os.path.exists(output_file):
print(f"O arquivo {output_file} já existe. Não é necessário combinar novamente.")
similarity = pickle.load(open("data/similarity_combined.pkl", 'rb'))
else:
# Juntar as 8 partes e salvar como um novo arquivo 'similarity_combined.pkl'
similarity = combine_files(part_count=8, output_file=output_file)
# Salvar o arquivo combinado
with open(output_file, 'wb') as f:
pickle.dump(similarity, f)
print(f"As partes foram combinadas e salvas em {output_file}.")
movies = pickle.load(open("data/movies_list.pkl", 'rb'))
movies_list=movies['title'].values
@app.route('/search_movies', methods=['GET'])
def search_movies():
query = request.args.get('q', '').lower() # Recebe a query do usuário e transforma em minúsculas
suggestions = []
# Filtra os filmes que contêm a string digitada (case-insensitive)
if query:
filtered_movies = [movie for movie in movies_list if query in movie.lower()][:5] # Limita a 5 sugestões
# Formata as sugestões no formato desejado
suggestions = [{'value': index + 1, 'text': movie} for index, movie in enumerate(filtered_movies)]
print(suggestions)
return jsonify(suggestions)
@app.route("/recommend")
def recommend():
movie = request.args.get("movie") # Receber o título do filme da solicitação
if movie is None:
return apology("Didn't insert movie title")
index = movies[movies['title'] == movie].index[0]
distance = sorted(list(enumerate(similarity[index])), reverse=True, key=lambda vector: vector[1])
recommendations = []
for i in distance[1:7]:
movies_id = movies.iloc[i[0]].id
title = movies.iloc[i[0]].title
poster = fetch_poster(movies_id)
recommendations.append({
"title": title,
"poster": poster
})
session["recommendations"] = recommendations # Armazenar as recomendações na sessão
return redirect("/") # Redirecionar para a página inicial
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def apology(message, code=400):
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [
("-", "--"),
(" ", "-"),
("_", "__"),
("?", "~q"),
("%", "~p"),
("#", "~h"),
("/", "~s"),
('"', "''"),
]:
s = s.replace(old, new)
return s
return render_template("apology.html", top=code, bottom=escape(message)), code
@app.route("/favorites", methods=["GET", "POST"])
@login_required
def favorites():
if request.method == "POST":
movie_title = request.form.get("movie")
# Busca o ID do filme através do título
movie = movies[movies['title'] == movie_title]
if not movie.empty:
print("movie: ", movie)
movie_id = movie.iloc[0]['id']
print("movie_id: ", movie_id)
# Adiciona o filme à tabela favorites
try:
cursor.execute(
"INSERT INTO favorites (user_id, title) VALUES (%s, %s)",
(session["user_id"], movie_title)
)
connection.commit() # Confirma a transação
flash(f'Filme "{movie_title}" adicionado aos favoritos!', 'success')
except Exception as e:
flash('Ocorreu um erro ao adicionar o filme aos favoritos. Tente novamente.', 'error')
print(e) # Para ajudar na depuração
else:
flash('Filme não encontrado. Verifique o título e tente novamente.', 'error')
# Busca os filmes favoritos do usuário
cursor.execute(
"SELECT title FROM favorites WHERE user_id = %s",
(session["user_id"],) # Usando current_user.id
)
favorite_movies = cursor.fetchall() # Obtém todos os filmes favoritos
print("favorite_movies: ", favorite_movies)
# Formata a lista para facilitar o uso no template
favorites_list = [{"title": movie[0], "id": movies[movies['title'] == movie[0]].iloc[0]['id']} for movie in favorite_movies]
print("favorites_list: ", favorites_list)
return render_template("favorites.html", favorites=favorites_list, fetch_poster=fetch_poster)
@app.route("/")
def index():
"""Renderizar a página inicial."""
recommendations = [] # Inicialize a lista de recomendações vazia
if "recommendations" in session: # Verifique se há recomendações na sessão
recommendations = session["recommendations"] # Recupere as recomendações
session.pop("recommendations") # Limpe a sessão após pegar as recomendações
return render_template("index.html", recommendations=recommendations) # Passe as recomendações para o template
@app.route("/recommend_by_favorites", methods=["POST"])
@login_required
def recommend_by_favorites():
cursor.execute(
"SELECT title FROM favorites WHERE user_id = %s",
(session["user_id"],) # Usando current_user.id
)
favorite_movies = cursor.fetchall() # Obtém todos os filmes favoritos
if len(favorite_movies) == 0:
return render_template("favorites.html")
# Formata a lista para facilitar o uso no template
favorites_list = [{"title": movie[0], "id": movies[movies['title'] == movie[0]].iloc[0]['id']} for movie in favorite_movies]
recommendations = []
for favorite in favorites_list:
movie_id = favorite["id"]
title = favorite["title"]
# Encontrar recomendações para cada filme favorito
index = movies[movies['id'] == movie_id].index[0]
distance = sorted(list(enumerate(similarity[index])), reverse=True, key=lambda vector: vector[1])
for i in distance[1:7]: # Pegue os 6 primeiros filmes recomendados
recommended_movie_id = movies.iloc[i[0]].id
recommended_movie_title = movies.iloc[i[0]].title
poster = fetch_poster(recommended_movie_id)
print("RRRR: ", recommendations)
recommendations.append({
"title": recommended_movie_title,
"poster": poster,
"reason": f"Because you like {title}" # Motivo da recomendação
})
session["recommendations"] = recommendations # Armazena as recomendações
return redirect("/") # Redireciona para a página inicial
@app.route("/login", methods=["GET", "POST"])
def login():
session.clear()
if request.method == "POST":
if not request.form.get("username"): return apology("must provide username", 403)
elif not request.form.get("password"): return apology("must provide password", 403)
cursor.execute(
"SELECT * FROM users WHERE username = %s", (request.form.get("username"),)
)
row = cursor.fetchone() # Uma única linha
if row is None or not check_password_hash(
row[2], request.form.get("password")
):
return apology("invalid username and/or password", 403)
session["user_id"] = row[0]
return redirect("/")
else:
return render_template("login.html")
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
username = request.form.get("username")
# Verifica se o nome de usuário já está em uso
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
rows = cursor.fetchall() # Obtém todas as linhas retornadas
if len(rows) > 0:
return apology("Username already in use.")
# Validações
if not username:
return apology("Please fill in the username field.")
if not request.form.get("password"):
return apology("Please fill in the password field.")
if request.form.get("password") != request.form.get("confirmation"):
return apology("Passwords do not match.")
print("HASH: ", generate_password_hash(request.form.get("password")))
# Inserir novo usuário
cursor.execute("INSERT INTO users (username, hash) VALUES (%s, %s)",
(username, generate_password_hash(request.form.get("password"))))
connection.commit() # Confirma a transação
return redirect("/login")
return render_template("register.html")