-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
309 lines (249 loc) · 8.07 KB
/
main.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
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
from typing import List, Union
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pymongo import MongoClient
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
import certifi
import pandas as pd
from surprise import Reader, Dataset, SVD
from recommend import get_not_seen_movie, recommend
reader = Reader()
ratings = pd.read_csv("data/ratings_small.csv")
movies = ratings.movieId
# print(movies)
data = Dataset.load_from_df(ratings[["userId", "movieId", "rating"]], reader)
# print(data)
# 학습/테스트 데이터 분리
train_set = data.build_full_trainset()
# print("----------")
# print(train_set)
# print("----------")
test_set = train_set.build_testset()
# print(test_set)
# print("----------")
# SVD(Singular Value Decomposition) : 특이값 분해
algo = SVD()
algo.fit(train_set)
# prediction = algo.test(test_set)
# print(prediction)
# print("END TEST")
# print(accuracy.rmse(prediction))
class Movies(BaseModel):
movieId: str
rating: float
class Item(BaseModel):
shortId: str
movieList: List[Movies]
app = FastAPI()
# cors 해결
# origins = [
# "https://cinemaster-four.herokuapp.com",
# "https://cinemaster-four.herokuapp.com:5000",
# ]
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
username = "Hyyena"
password = "TxOPQ4CyleYvXi8D"
client = MongoClient(
"mongodb+srv://%s:%s@cinemaster.edkazqq.mongodb.net/cinema?retryWrites=true&w=majority" % (username, password), tlsCAFile=certifi.where())
print(client.list_database_names())
db = client.cinema
print(db)
print(db.users)
##
# 유저별 추천 영화 목록 조회
##
@app.get(
"/recommendation/{shortId}",
responses={
200: {
"description": "추천 영화 목록 조회 성공",
"content": {
"application/json": {
"example": {
"recommendList": [
{
"movieId": 31,
"star": 3.3
},
{
"movieId": 1029,
"star": 3.7
},
{
"movieId": 1061,
"star": 3.6
}
]
}
}
}
}
}
)
async def recommend_movie(shortId: str):
recommends = db.recommends
auth_data = db.users.find_one({"shortId": shortId}, {"_id": 0})
print("111 : ", auth_data)
if not auth_data:
raise HTTPException(status_code=404, detail="User not found")
recommend_data = recommends.find_one({"userRef": auth_data})
print("222 : ", recommend_data)
if not recommend_data:
return JSONResponse(content={"result": "추천 영화 목록 조회 실패"})
else:
# recommends collection에서 랜덤 데이터 추출
pipeline = [
{"$match": {"userRef": auth_data}},
{"$unwind": "$recommendList"},
{"$sample": {"size": 20}}
]
random_data = recommends.aggregate(pipeline)
result = []
for data in random_data:
result.append(data["recommendList"])
result = jsonable_encoder(result)
print(type(JSONResponse(content={"recommendList": result})))
print(JSONResponse(result))
# return {"recommendList": result}
return JSONResponse(content={"recommendList": result})
##
# 평가할 영화 랜덤 조회
##
@app.get(
"/eval/{movieCount}",
responses={
200: {
"description": "랜덤 평가 영화 조회 성공",
"content": {
"application/json": {
"example": {
"movieNum": 3,
"result": [
{
"movieId": 5418
},
{
"movieId": 1307
},
{
"movieId": 1221
}
]
}
}
}
}
}
)
async def random_movie(movieCount: int):
# CSV 파일에서 movieCount 만큼 랜덤 추출
df = ratings.sample(movieCount, replace=False)
# DataFrame을 Numpy 배열로 변환
col_movie_id = df["movieId"].to_numpy()
col_rating = df["rating"].to_numpy()
# Numpy 배열을 list로 변환
movie_id = col_movie_id.tolist()
rating = col_rating.tolist()
result = []
for movieId in movie_id:
# dict = {"movieId": movieId}
# result.append(dict)
result.append(movieId)
print(result)
result = jsonable_encoder(result)
# return {"movieNum": movieCount, "result": result}
return JSONResponse(content={"movieNum": movieCount, "result": result})
##
# 평가 데이터 저장
##
@app.post(
"/eval",
responses={
200: {
"description": "평가 영화 제출 완료!",
"content": {
"application/json": {
"example": {
"shortId": "shortId",
"result": [
{
"movieId": "37550",
"star": 2
},
{
"movieId": "862",
"star": 3.5
},
{
"movieId": "3525",
"star": 0.5
}
]
}
}
}
}
}
)
async def write_movie(item: Item):
short_id = item.shortId
auth_data = db.users.find_one({"shortId": short_id}, {"_id": 0})
print(auth_data)
if not auth_data:
raise HTTPException(status_code=404, detail="User not found")
movie_arr = []
rating_arr = []
# 빈 배열에 요청 받은 영화 ID와 평점을 저장
for movie in item.movieList:
movie_arr.append(movie.movieId)
rating_arr.append(movie.rating)
print(movie_arr)
print(rating_arr)
# 영화 ID와 평점 배열을 DataFrame으로 변환
df = pd.DataFrame(
{"userId": short_id, "movieId": movie_arr, "rating": rating_arr})
# 변환한 DataFrame을 기존 DataFrame에 추가
new_df = ratings.append(df, ignore_index=True)
# 새로운 DataFrame을 CSV 파일로 저장
new_df.to_csv("data/ratings_small.csv", index=False)
result = []
for movie_id, rating in zip(movie_arr, rating_arr):
dict = {"movieId": movie_id, "star": rating}
result.append(dict)
print(result)
recommends = db.recommends
# ---------- 추천 알고리즘 ----------
userId = short_id
top_n = 300
not_seen_list = get_not_seen_movie(ratings, movies, userId)
top_movies_preds = recommend(algo, userId, not_seen_list, top_n)
recommend_list = []
for top_movie in top_movies_preds:
dict = {"movieId": top_movie[0], "star": top_movie[1]}
recommend_list.append(dict)
# print(recommend_list)
# ----------------------------------------
print("recommend_list : ", recommend_list)
# document create & update
recommends.find_one_and_update(
{"userRef": auth_data},
{"$set": {"userRef": auth_data, "recommendList": recommend_list}},
upsert=True
)
result = jsonable_encoder(result)
print("result", result)
# return {"shortId": short_id, "result": result}
return JSONResponse(content={"shortId": short_id, "result": result})
# if __name__ == "__main__":
# import uvicorn
# uvicorn.run("main:app")