def logout(user_id, user_token): try: pass # if not ObjectId.is_valid(user_id): # raise Exception("Invalid Id") # # if system_users_authentication_check(user_id, user_token)["Description"] == "Exists": # same_user = user_collection.find_one({"_id": ObjectId(user_id)}) # if not same_user: # raise Exception("This user not exists") # return system_users_authentication_logout(user_id, user_token) # else: # raise Exception("Permission denied") except Exception as ex: return Tools.Result(False, ex.args)
def get_events_sorted(): event_object = event_collection.find({}) events = [] for event in event_object: events.append(event) passed_events = [] upcoming_events = [] for event in events: event_image_id = event['ImageUrl']['ImageId'] event[ 'ImageUrl'] = 'https://cafe-art-backend.liara.run/event/image/{}'.format( event_image_id) event_date = event['Date'] splitted = event_date.split('/') year = int(splitted[0]) month = int(splitted[1]) day = int(splitted[2]) cr_date = jdatetime.date(year, month, day).togregorian() if cr_date < datetime.now().date(): passed_events.append({'sdate': cr_date, 'Event': event}) else: upcoming_events.append({'sdate': cr_date, 'Event': event}) passed_events = sorted(passed_events, key=lambda i: i['sdate']) upcoming_events = sorted(upcoming_events, key=lambda i: i['sdate']) response = { 'PassedEvents': passed_events, 'UpcomingEvents': upcoming_events } return Tools.Result(True, Tools.dumps(response))
def complete_sign_up(phone_number, name=None, birthdate=None, gender=None): # validate phone number if User.validate_phone(phone_number) is None: return Tools.Result(False, Tools.errors('NA')) # make sure user with specified phone number is registered and confirmed user_object = user_collection.find_one( {'PhoneNumber': phone_number # 'Status': 'Confirm' }, {'_id': 1}) if user_object is None: return Tools.Result(False, Tools.errors('INF')) user_collection.update_one( {'PhoneNumber': phone_number}, {'$set': { 'Name': name, 'Birthdate': birthdate, 'Gender': gender }}) return Tools.Result(True, 'd')
def modify_item(): try: data = request.get_json() return Item.modify_item( data['ItemId'], data['RowId'] if 'RowId' in data else None, data['CategoryName'] if 'CategoryName' in data else None, data['Title'] if 'Title' in data else None, data['Description'] if 'Description' in data else None, data['Price'] if 'Price' in data else None, data['MenuImageUrl'] if 'MenuImageUrl' in data else None, data['ItemImageUrl'] if 'ItemImageUrl' in data else None) except Exception as ex: import traceback traceback.print_exc() return Tools.Result(False, ex.args)
def is_login(headers): try: user_id = headers["Id"] user_token = headers["Token"] result = requests.get( "http://localhost:3001/system/users/authentication/check", headers={ "Id": user_id, "Token": user_token }).content result = json.loads(result) print(result) if result["Description"] != "accepted": raise Exception("Login Required") except Exception as ex: return Tools.Result(False, ex.args)
def get_user_info(): try: is_login(request.headers) # if not ObjectId.is_valid(user_id): # raise Exception("Invalid Id") # # if system_users_authentication_check(user_id, user_token): # same_user = user_collection.find_one({"_id": ObjectId(user_id), UserModelVN.Token: user_token}) # if not same_user: # raise Exception("This user not exist") # return Tools.Result(True, same_user) # else: # raise Exception("Permission denied") except Exception as ex: return Tools.Result(False, ex.args)
def modify_item(item_id, row_id=None, category_name=None, title=None, description=None, price=None, menu_image_url=None, item_image_url=None): # make sure at least on attribute is not null if row_id is None and category_name is None and title is None and price is None and menu_image_url is None and item_image_url is None and description is None: return Tools.Result(False, Tools.errors('NA')) if (row_id is None and category_name is not None) or (row_id is not None and category_name is None): return Tools.Result(False, Tools.errors('NA')) valid = item_collection.find_one({'_id': ObjectId(item_id)}, {'_id': 1}) is not None if not valid: return Tools.Result(False, Tools.errors('INF')) updating_values = {} if title is not None: updating_values['Title'] = title if row_id is not None: updating_values['RowId'] = str(row_id) updating_values['CategoryName'] = category_name if price is not None: updating_values['Price'] = price if menu_image_url is not None: updating_values['MenuImageUrl.MenuImage'] = menu_image_url if item_image_url is not None: updating_values['ItemImageUrl.ItemImage'] = item_image_url if description is not None: updating_values['Description'] = description item_collection.update_one({'_id': ObjectId(item_id)}, {'$set': { **updating_values }}) return Tools.Result(True, 'd')
def add_image_gallery(item_id, gallery): gallery_objects = [] for item in gallery: gallery_objects.append({ 'ImageUrl': item, 'Likes': [], 'LikesCount': 0, 'Id': str(ObjectId()) }) item_collection.update_one( {'_id': ObjectId(item_id)}, {'$push': { 'Gallery': { '$each': gallery_objects } }}) return Tools.Result(True, 'd')
def update_user_info(user_id, user_token, new_data): try: if not ObjectId.is_valid(user_id): raise Exception("Invalid id") # if system_users_authentication_check(user_id, user_token)["Description"] == "Exists": # same_user = user_collection.find_one({"_id": ObjectId(user_id), UserModelVN.Token: user_token}) # if not same_user: # raise Exception("This user not exist") # else: # user_collection.update_one({"_id": ObjectId(user_id)}, { # "$set": {UserModelVN.Fname: new_data[UserModelVN.Fname], # UserModelVN.Lname: new_data[UserModelVN.Lname], # UserModelVN.Gender: new_data[UserModelVN.Gender]}}) # return Tools.Result(True, "Done") else: raise Exception("Permission denied") except Exception as ex: return Tools.Result(False, ex.args)
def login_verification(phone_number, verification_code): # validate phone number and activation code if (re.match(User.Constants.phone_regex, phone_number) is None or re.match(User.Constants.activation_code_regex, str(verification_code)) is None): return Tools.Result(False, Tools.errors('NA')) # check whether user is registered and is assigned the specified activation code # also make sure code is not used before user_object = user_collection.find_one( { 'PhoneNumber': phone_number, 'Code.Code': int(verification_code), 'Code.Is_Used': False }, {'_id': 1}) if user_object is None: return Tools.Result(False, Tools.errors('INF')) # update user status to confirmed user_collection.update_one({'PhoneNumber': phone_number}, { '$set': { 'Update_at': datetime.now(), 'Status': 'Confirm', 'Code.Is_Used': True, 'IsActive': True } }) token = Auth.add_token(user_id=str(user_object["_id"])) if not token: return Tools.Result(False, Tools.errors("FTGT")) response = {'Id': user_object["_id"], 'Token': token} return Tools.Result(True, Tools.dumps(response))
def register_admin(): firstname = 'admin' lastname = 'admin' username = '******' password = '******' key = Fernet.generate_key() fernet = Fernet(key) admin_collection.insert_one({ 'UserName': username, 'Password': fernet.encrypt(password.encode()), 'FirstName': firstname, 'LastName': lastname, 'Key': key }) return Tools.Result(True, 'd')
class Data(): def __init__(self): ############################################################### # # Sets up all default requirements and placeholders # needed for the Acute Myeloid Leukemia Classifier. # ############################################################### self.Tools = Tools() self.confs = self.Tools.loadConfs() self.fixed = tuple((self.confs["Settings"]["ImgDims"], self.confs["Settings"]["ImgDims"])) def writeImage(self, filename, image): ############################################################### # # Writes an image based on the filepath and the image provided. # ############################################################### cv2.imwrite(filename, image) def resize(self, filePath, savePath, show=False): ############################################################### # # Writes an image based on the filepath and the image provided. # ############################################################### image = cv2.resize(cv2.imread(filePath), self.fixed) self.writeImage(savePath, image) if show is True: print(savePath) plt.imshow(image) plt.show() return image def grayScale(self, image, grayPath, show=False): ############################################################### # # Writes a grayscale copy of the image to the filepath provided. # ############################################################### gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) self.writeImage(grayPath, gray) if show is True: print(grayPath) plt.imshow(gray) plt.show() return image, gray def equalizeHist(self, gray, histPath, show=False): ############################################################### # # Writes histogram equalized copy of the image to the filepath # provided. # ############################################################### hist = cv2.equalizeHist(gray) self.writeImage(histPath, cv2.equalizeHist(gray)) if show is True: print(histPath) plt.imshow(hist) plt.show() return hist def reflection(self, image, horPath, verPath, show=False): ############################################################### # # Writes histogram equalized copy of the image to the filepath # provided. # ############################################################### horImg = cv2.flip(image, 0) self.writeImage(horPath, horImg) if show is True: print(horPath) plt.imshow(horImg) plt.show() verImg = cv2.flip(image, 1) self.writeImage(verPath, verImg) if show is True: print(verPath) plt.imshow(verImg) plt.show() return horImg, verImg def gaussian(self, filePath, gaussianPath, show=False): ############################################################### # # Writes gaussian blurred copy of the image to the filepath # provided. # ############################################################### gaussianBlur = ndimage.gaussian_filter(plt.imread(filePath), sigma=5.11) self.writeImage(gaussianPath, gaussianBlur) if show is True: print(gaussianPath) plt.imshow(gaussianBlur) plt.show() return gaussianBlur def rotation(self, path, filePath, filename, show=False): ############################################################### # # Writes rotated copies of the image to the filepath # provided. # ############################################################### img = Image.open(filePath) for i in range(1, 10): randDeg = random.randint(-180, 180) fullPath = os.path.join(path, str(randDeg) + '-' + filename) if show is True: print(fullPath) img.rotate(randDeg, expand=True).resize( (self.confs["Settings"]["ImgDims"], self.confs["Settings"]["ImgDims"])).save(fullPath).show() else: print(fullPath) img.rotate(randDeg, expand=True).resize( (self.confs["Settings"]["ImgDims"], self.confs["Settings"]["ImgDims"])).save(fullPath) def processDataset(self): ############################################################### # # Runs all of the above functions saving the new dataset to the # default training directory. # ############################################################### for directory in os.listdir(self.confs["Settings"]["TrainDir"]): if os.path.isdir( os.path.join(self.confs["Settings"]["TrainDir"], directory)): path = os.path.join(self.confs["Settings"]["TrainDir"], directory) sortedPath = os.path.join( self.confs["Settings"]["TrainDir"] + "augmented/", directory) fCount = 0 for filename in os.listdir(path): if filename.endswith('.jpg'): filePath = os.path.join(path, filename) image = self.resize(filePath, sortedPath + "/" + filename, True) image, gray = self.grayScale( image, os.path.join(sortedPath, "Gray-" + filename), True) hist = self.equalizeHist( gray, os.path.join(sortedPath, "Hist-" + filename), True) horImg, verImg = self.reflection( image, os.path.join(sortedPath, "Hor-" + filename), os.path.join(sortedPath, "Ver-" + filename), True) gaussianBlur = self.gaussian( filePath, os.path.join(sortedPath, "Gaus-" + filename), True) self.rotation(sortedPath, filePath, filename) fCount += 1 else: continue print(" AML-DNN: " + self.Tools.currentDateTime() + " - Added filters to " + str(fCount) + " files in " + str(directory))
def get_activation_code(phone_number): try: return User.get_activation_code(phone_number) except Exception as ex: return Tools.Result(False, ex.args)
def get_events(): try: return Event.get_events() except Exception as ex: return Tools.Result(False, ex.args)
def get_event_image(image_id): try: return Event.get_event_image(image_id) except Exception as ex: return Tools.Result(False, ex.args)
def get_item_menu_image(image_id): try: return Item.get_item_menu_image(image_id) except Exception as ex: return Tools.Result(False, ex.args)
def delete_event(): try: data = request.get_json() return Event.delete_event(data['EventId']) except Exception as ex: return Tools.Result(False, ex.args)
def add(sender_id, receiver_id, url, type): try: pass except Exception as ex: return Tools.Result(False, ex.args)
def delete_image(): try: data = request.get_json() return Cafe.delete_image(data['ImageId']) except Exception as ex: return Tools.Result(False, ex.args)
def edit(message_id, new_data): try: pass except Exception as ex: return Tools.Result(False, ex.args)
def delete(message_id): try: pass except Exception as ex: return Tools.Result(False, ex.args)
def get_all_items(): try: return Item.get_all_items() except Exception as ex: return Tools.Result(False, ex.args)
def push_notification(admin_id, title, date, description): notification_collection.insert_one( Notification(admin_id, title, date, description).__dict__) return Tools.Result(True, 'd')
def get_image_urls(): try: return Cafe.get_image_urls() except Exception as ex: return Tools.Result(False, ex.args)
def login_as_guest(): try: data = request.get_json() return User.login_as_guest(data['UUID']) except Exception as ex: return Tools.Result(False, ex.args)
def test(): return Tools.Result(True, 'test')
def login_verification(): try: data = request.get_json() return User.login_verification(data['PhoneNumber'], data['VerificationCode']) except Exception as ex: return Tools.Result(False, ex.args)
def toolOBJ(tool): tool = Tools() return tool