-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
567 lines (472 loc) · 19.9 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
from datalayer.clothes_db import *
from datalayer.users_db import *
from datalayer.calendar_db import *
from algorithm.color_algo import GetStyleOutfits
from algorithm.color_detection_camera import dominant_color_finder_dataurl
import logging
logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)
import base64
from PIL import Image
from io import BytesIO
import os
from os import environ as env
from flask import Flask, render_template, request, session, redirect, url_for, jsonify
import uuid
from datetime import datetime
today = datetime.now()
from dotenv import find_dotenv, load_dotenv
from authlib.integrations.flask_client import OAuth
from urllib.parse import quote_plus, urlencode
import configparser
config = configparser.ConfigParser()
config.read('config.properties')
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
else:
print("ERROR: .env FILE NOT FOUND CANNOT CONNECT TO DB AND AUTH0")
app = Flask(__name__)
app.secret_key = env.get("APP_SECRET_KEY")
oauth = OAuth(app)
oauth.register(
"auth0",
client_id=env.get("AUTH0_CLIENT_ID"),
client_secret=env.get("AUTH0_CLIENT_SECRET"),
client_kwargs={
"scope": "openid profile email",
},
server_metadata_url=f'https://{env.get("AUTH0_DOMAIN")}/.well-known/openid-configuration'
)
if config.get("DEFAULT", "DEVTYPE") == "aws":
import boto3
s3 = boto3.client('s3')
CLOTHING_BUCKET_NAME = "poshify-clothingimages"
WEEKDAYS_NUM2DAY = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
WEEKDAYS_DAY2NUM = {"Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, "Friday": 4, "Saturday": 5, "Sunday": 6}
DAYS_IN_MONTH = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31, }
@app.route("/")
@app.route("/home")
def home():
return render_template("home.html", session=session.get('user'))
@app.route("/signup", methods=["POST", "GET"])
def signup():
return oauth.auth0.authorize_redirect(
redirect_uri=url_for("callback_signup", _external=True),
screen_hint="signup"
)
@app.route("/login", methods=["POST", "GET"])
def login():
return oauth.auth0.authorize_redirect(
redirect_uri=url_for("callback_login", _external=True),
screen_hint="login"
)
@app.route("/callback_login", methods=["GET", "POST"])
def callback_login():
print('LOGIN')
token = oauth.auth0.authorize_access_token()
session["user"] = token
session["userid"] = token['userinfo']['sub'][14:]
phone_number = None
password = None
user_id = session.get("userid")
user_photo_file_name = token['userinfo']['picture']
email = token['userinfo']['email']
missingInfo = []
if 'nickname' not in token['userinfo']:
missingInfo.append('nickname')
else:
username = token['userinfo']['nickname']
if 'given_name' not in token['userinfo']:
missingInfo.append('given_name')
else:
first_name = token['userinfo']['given_name']
if 'family_name' not in token['userinfo']:
missingInfo.append('family_name')
else:
last_name = token['userinfo']['family_name']
session['missingInfo'] = missingInfo
if len(missingInfo) == 0:
create_user(user_id=user_id, username=username, password=password, first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, user_photo_file_name=user_photo_file_name)
else:
return render_template('onboarding.html', session=session['user'], user_id=session['userid'], missingInfo=missingInfo)
return redirect("/dashboard")
@app.route("/callback_signup", methods=["GET", "POST"])
def callback_signup():
print('SIGNUP')
token = oauth.auth0.authorize_access_token()
session["user"] = token
session["userid"] = token['userinfo']['sub'][14:]
phone_number = ""
password = ""
user_id = session.get("userid")
user_photo_file_name = token['userinfo']['picture']
email = token['userinfo']['email']
missingInfo = []
if 'nickname' not in token['userinfo']:
missingInfo.append('nickname')
else:
username = token['userinfo']['nickname']
if 'given_name' not in token['userinfo']:
missingInfo.append('given_name')
else:
first_name = token['userinfo']['given_name']
if 'family_name' not in token['userinfo']:
missingInfo.append('family_name')
else:
last_name = token['userinfo']['family_name']
session['missingInfo'] = missingInfo
if len(missingInfo) == 0:
create_user(user_id=user_id, username=username, password=password, first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, user_photo_file_name=user_photo_file_name)
else:
create_user(user_id=user_id, username=token['userinfo'].get('nickname'), password=password, first_name=token['userinfo'].get('given_name'), last_name=token['userinfo'].get('family_name'), email=email, phone_number=phone_number, user_photo_file_name=user_photo_file_name)
return render_template('onboarding.html', session=session['user'], user_id=session['userid'], missingInfo=missingInfo)
return redirect("/dashboard")
@app.route('/onboarding', methods=['POST'])
def onboarding():
print('started')
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
missingInfo = session['missingInfo']
if len(missingInfo) == 0:
return render_template("dashboard.html", session=session['user'], user_id=session['userid'])
if request.method == 'POST':
for info in missingInfo:
user_data_to_add_to_db = request.form.get(info)
if user_data_to_add_to_db is None:
return render_template("onboarding.html", missingInfo=missingInfo, result="Add all user info")
update_data_given_row(session['userid'], info, user_data_to_add_to_db)
return render_template("dashboard.html", session=session['user'], user_id=session['userid'])
return render_template("onboarding.html", session=session['user'], user_id=session['userid'], missingInfo=missingInfo)
@app.route("/logout")
def logout():
session.clear()
return redirect(
"https://" + env.get("AUTH0_DOMAIN")
+ "/v2/logout?"
+ urlencode(
{
"returnTo": url_for("home", _external=True),
"client_id": env.get("AUTH0_CLIENT_ID"),
},
quote_via=quote_plus,
)
)
@app.route("/dashboard", methods=["POST", "GET"])
def dashboard():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
return render_template("dashboard.html", session=user, user_id=user_id)
@app.route("/closet", methods=["POST", "GET"])
def closet():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
clothes = get_clothing_name_image_id_by_user_id(user_id)
filters = [[] for i in range(3)]
if 'filters' in session:
filters = session['filters']
return render_template("closet.html", session=user, user_id=user_id, clothes=clothes, filters=filters, config=config.get("DEFAULT", "DEVTYPE"))
@app.route("/outfits", methods=["POST", "GET"])
def generate_fit():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
# sunny
hats = get_clothing_by_type(user_id, "Hat")
# cold
jackets = get_clothing_by_type(user_id, "Jacket")
# hot
tshirts = get_clothing_by_type(user_id, "T-Shirt")
# mid - cold
sweatshirts = get_clothing_by_type(user_id, "Sweatshirt")
# mid - cold
pants = get_clothing_by_type(user_id, "Pant")
# hot
shorts = get_clothing_by_type(user_id, "Short")
# cold - hot
shoes = get_clothing_by_type(user_id, "Shoe")
tops = jackets + tshirts + sweatshirts
bots = pants + shorts
calendarInfo, cloth_ids = get_image_paths_per_day(user_id)
outfits = GetStyleOutfits(tops, bots, shoes, calendarInfo, cloth_ids)
weekday = (today.isoweekday() - 1) % 7
day = WEEKDAYS_NUM2DAY[weekday]
if calendarInfo:
return render_template("outfits.html", session=user, user_id=user_id, outfits=outfits, calendarInfo = calendarInfo, config=config.get("DEFAULT", "DEVTYPE"), weekday=weekday, day=day)
else:
return render_template("outfits.html", session=user, user_id=user_id, outfits=outfits, config=config.get("DEFAULT", "DEVTYPE"), weekday=weekday, day=day)
@app.route("/settings", methods=["POST", "GET"])
def settings():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
return render_template("settings.html", session=user, user_id=user_id)
@app.route("/add_clothing_manual", methods=['POST', "GET"])
def add_clothing_manual():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'POST':
clothing_name = request.form['clothing_name']
clothing_type = request.form['clothes_type']
is_clean = request.form['is_clean'] == "y"
until_dirty = None if is_clean else 0
image_file = request.files['image']
has_name = has_clothing_name_by_id(clothing_name, user_id)
if has_name:
return render_template("add_clothing_manual.html", session=user, result="Name already exists for cloth", user_id=user_id)
if clothing_name is None or clothing_type is None or is_clean is None or image_file is None:
return render_template("add_clothing_manual.html", session=user, result="All data fields not entered", user_id=user_id)
if image_file.filename == '':
return render_template("add_clothing_manual.html", result="No Selected File", session=user, user_id=user_id)
try:
filename = str(uuid.uuid4()) + os.path.splitext(image_file.filename)[1]
image_data = image_file.read()
encoded_image = base64.b64encode(image_data).decode('utf-8')
dominant_color = dominant_color_finder_dataurl(encoded_image)
hue = dominant_color[0]
saturation = dominant_color[1]
value = dominant_color[2]
result = create_cloth(user_id, clothing_name, clothing_type, is_clean, hue, saturation, value, filename, until_dirty=until_dirty)
if config.get("DEFAULT", "DEVTYPE") == "local":
with open(os.path.join('static/clothing_images/', filename), 'wb') as f:
f.write(image_data)
else:
image_file.seek(0)
s3.upload_fileobj(
image_file,
CLOTHING_BUCKET_NAME,
f'clothing_images/{filename}',
ExtraArgs={'ContentType': 'image/jpeg'}
)
return render_template("add_clothing_manual.html", result=result, session=user, user_id=user_id)
except Exception as e:
return render_template("add_clothing_manual.html", result="Add clothing error", session=user, user_id=user_id)
return render_template("add_clothing_manual.html", session=user, result="", user_id=user_id)
@app.route("/add_clothing_camera", methods=["POST", "GET"])
def add_clothing_camera():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'POST':
clothing_name = request.form['clothing_name']
clothing_type = request.form['clothes_type']
is_clean = request.form['is_clean']
image_data = request.form['imageData']
if (is_clean == "y"):
is_clean = True
else:
is_clean = False
has_name = has_clothing_name_by_id(clothing_name, user_id)
if has_name:
return render_template("add_clothing_camera.html", session=user, result="Name already exists for cloth", user_id=user_id)
if clothing_name is None or clothing_type is None or is_clean is None or image_data is None:
return render_template("add_clothing_camera.html", session=user, result="All data fields not entered", user_id=user_id)
if not image_data:
return render_template("add_clothing_camera.html", result="Camera Data invalid or not working", user_id=user_id)
try:
filename = str(uuid.uuid4()) + ".jpeg"
hue, saturation, value = dominant_color_finder_dataurl(image_data)
image_binary = base64.b64decode(image_data)
img = Image.open(BytesIO(image_binary))
if config.get("DEFAULT", "DEVTYPE") == "local":
img.save(os.path.join('static/clothing_images', filename), "JPEG")
else:
s3.put_object(Body=image_binary, Bucket=CLOTHING_BUCKET_NAME, Key=f"clothing_images/{filename}")
result = create_cloth(user_id, clothing_name, clothing_type, is_clean, hue, saturation, value, filename)
return render_template("add_clothing_camera.html", session=user, result=f"Added {clothing_name}", user_id=user_id)
except Exception as e:
print(f"add_clothing_camera ERROR: {e}")
return render_template("add_clothing_camera.html", session=user, result="ERROR: Could not add clothign", user_id=user_id)
return render_template("add_clothing_camera.html", session=user, user_id=user_id)
@app.route('/update', methods=['POST'])
def update_element():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'POST':
data = request.get_json()
updated_text = data.get('updatedText')
has_name = has_clothing_name_by_id(updated_text, user_id)
clothing_name = data.get('identifier')
if updated_text.lower() == clothing_name.lower():
response_data = {
'identifier': updated_text,
'message': 'Same name'
}
update_clothing_name_by_clothing_name(clothing_name, updated_text, user_id)
return jsonify(response_data), 200
elif has_name:
response_data = {
'identifier': clothing_name,
'message': 'Name exists'
}
return jsonify(response_data), 200
user = session.get("user")
user_id = session.get('userid')
update_clothing_name_by_clothing_name(clothing_name, updated_text, user_id)
response_data = {
'identifier': updated_text,
'message': 'Updated successfully'
}
return jsonify(response_data), 200
else:
return 'Invalid request', 400
@app.route('/update_cleanliness', methods=['POST'])
def update_cleanliness():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'POST':
data = request.get_json()
clothid = data.get('clothesId')
new_status = data.get('cleanlinessStatus')
update_cleanliness_status(clothid, new_status)
response_data = {
'clothid': clothid,
'message': 'Updated successfully'
}
return jsonify(response_data), 200
@app.route('/closet_delete_cloth', methods=['DELETE'])
def delete_element():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'DELETE':
data = request.get_json()
clothes_id = data.get('clothes_id')
user_id = session.get('userid')
url = delete_clothing_by_id(clothes_id, user_id)
if config.get("DEFAULT", "DEVTYPE") == "local":
filepath = os.path.join("static/clothing_images", url)
if os.path.exists(filepath):
os.remove(filepath)
else:
s3.delete_object(Bucket=CLOTHING_BUCKET_NAME, Key=f'clothing_images/{url}')
delete_clothing_by_id(clothes_id, user_id)
return jsonify({'message': f'{clothes_id} deleted successfully'}), 200
else:
return jsonify({'message': 'Method not allowed'}), 405
@app.route("/update_filters", methods=["POST"])
def update_filters():
user = session.get("user")
if not user:
print("ERROR: USER NOT LOGGED IN")
return redirect("/home", code=302)
user_id = session.get('userid')
if not user_id:
print("ERROR: NO ID_TOKEN FOUND")
return redirect("/home", code=302)
if request.method == 'POST':
filter_data = request.get_json()
articles_data = filter_data.get('articles')
session['filters'] = [articles_data]
return ({'message': f'{articles_data} filter added successfully'}), 200
@app.route('/save_calendar_outfit', methods=['POST'])
def save_outfit():
try:
outfit_data = request.json
user_id = session.get('userid')
clothes_id = outfit_data.get('clothes_id')
day_of_week = outfit_data.get('day_of_week')
image_paths = outfit_data.get('image_paths')
outfit_type = outfit_data.get('outfitType')
todayDayNum = today.isoweekday() # eg. if sunday its 7
insertedDayNum = WEEKDAYS_DAY2NUM[day_of_week] + 1 # eg. if wednesday this gives 3
daysForward = (todayDayNum + insertedDayNum) % 7
day = int(today.strftime("%d"))
month = int(today.strftime("%m"))
year = int(today.strftime("%y"))
daysInMonth = DAYS_IN_MONTH[month]
if month == 2 and year % 4 == 0:
daysInMonth += 1
newDay = day + daysForward
if newDay > daysInMonth:
newDay %= daysInMonth
month += 1
if month > 12:
month %= 12
year += 1
newDay = str(newDay)
if len(newDay) <= 1:
newDay = "0" + newDay
month = str(month)
if len(month) <= 1:
month = "0" + month
year = str(year)
if len(year) <= 1:
year = "0" + year
date = f"{newDay}{month}{year}"
create_calendar_entry(user_id, clothes_id, day_of_week, image_paths, outfit_type, date)
return 'Outfit data received and saved successfully.', 200
except Exception as e:
print(f"Error saving outfit data: {str(e)}")
return 'Failed to process outfit data.', 500
@app.route('/delete_outfit', methods=['POST'])
def delete_outfit():
try:
outfit_data = request.json
user_id = session.get('userid')
day_of_week = outfit_data.get('day_of_week')
image_paths = outfit_data.get('image_paths')
outfit_type = outfit_data.get('outfitType')
delete_entry(user_id, day_of_week, image_paths[0], outfit_type)
delete_entry(user_id, day_of_week, image_paths[1], outfit_type)
delete_entry(user_id, day_of_week, image_paths[2], outfit_type)
return 'Outfit data received and saved successfully.', 200
except Exception as e:
return 'Failed to process outfit data.', 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=config.get("DEFAULT", "PORT"))