def get_avg_pass_route_stop(): """ TODO: """ db = get_db() data = list(db.get_avg_route_stop())[:100] return jsonify({'results': data})
def go_album(): # Check whether the user is logged in username = session.get('username') if username is None: flash('Please log in first') return redirect(url_for('login')) else: # Show all thumbnails of the users cnx = get_db() cursor = cnx.cursor() query = 'SELECT key2 from photos WHERE userID = %s' cursor.execute(query, (username,)) thumbnails = [item[0] for item in cursor.fetchall()] urls = [] for key in thumbnails: s3 = boto3.client('s3') normName = normalName(key) user_len = len(session.get('username')) normName = normName[user_len+1: ] url = s3.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': S3_BUCKET, 'Key': key } ) urls.append([url, key, normName]) return render_template('myalbum.html', urls=urls)
def get_records_num(): """ TODO: """ db = get_db() number = db.get_loc_count() return jsonify({'num_of_records': number})
def view_as_plcy(): cnx = get_db() cursor = cnx.cursor() query = "SELECT * FROM aspolicy" cursor.execute(query) return render_template('autoscaling/list.html', title="Auto Scaling policy", cursor=cursor)
def getTransforms(id): data = [] query = "SELECT * from images where userId=%s and id=%s" cnx = get_db() cursor = cnx.cursor() cursor.execute(query, (session['userid'], id)) rows = cursor.fetchall() return jsonify({'rows': rows})
def getImage(): data = [] query = "SELECT key1 from images where userId=%s" cnx = get_db() cursor = cnx.cursor() cursor.execute(query, (session['userid'], )) rows = cursor.fetchall() return jsonify({'rows': rows})
def update_imagesdb(imgObj, id): query = "UPDATE images set key1=%s,key2=%s,key3=%s,key4=%s where id=%s" cnx = get_db() cursor = cnx.cursor() cursor.execute( query, (imgObj['key1'], imgObj['key2'], imgObj['key3'], imgObj['key4'], id)) cnx.commit() return
def get_track_days(): """ Returns number difference betwwen first and last record date in DB. Returs {'days': <NUMBER>} """ db = get_db() return jsonify({'days': db.get_days_of_tracking()})
def viewImage(key): cnx = get_db() cursor = cnx.cursor() query = ''' select key0, key1 from photos where key2 = %s ''' cursor.execute(query, (key, )) keys = cursor.fetchone() url0 = url_for('static', filename='uploads/' + keys[0]) url1 = url_for('static', filename='uploads/' + keys[1]) return render_template("/twoImages.html", key0=url0, key1=url1)
def editPolicyStatus(): cnx = get_db() cursor = cnx.cursor() query = ''' UPDATE aspolicy set parameter_val=%s where parameter_nm=%s ''' cursor.execute(query, (request.args.get('plcy_status', type=int), 'plcy_status')) cnx.commit() return jsonify(data="Policy has been saved successfully")
def get_routes_num(): """ Returns number of routes that have tracked. Get {'NumOfRoute': <NUMBER>} from DB but returns {'num_of_routes': <NUMBER>} to follow same name convention """ db = get_db() number = db.get_number_of_routes() return jsonify({'num_of_routes': number.get('NumOfRoute')})
def insert_to_imagesdb(imgObj): query = "INSERT into images (userId,key1,key2,key3,key4) VALUES (%s,%s,%s,%s,%s)" cnx = get_db() cursor = cnx.cursor() cursor.execute(query, (imgObj['userid'], imgObj['key1'], imgObj['key2'], imgObj['key3'], imgObj['key4'])) cnx.commit() query = "SELECT id from images where userId=%s and key1=%s and key2=%s and key3=%s and key4=%s" cursor.execute(query, (imgObj['userid'], imgObj['key1'], imgObj['key2'], imgObj['key3'], imgObj['key4'])) row = cursor.fetchone() return row[0]
def get_route_names(): """ Returns all possible route names for routes that have tracked. Get something like this {"routes": ["100A", "8A"]} """ db = get_db() cursor = db.get_all_routes_name() routes = [route for route in cursor][:5] return jsonify({'routes': routes})
def image_list(): cnx = get_db() cursor = cnx.cursor() query = "SELECT * FROM images WHERE userId = %s" images = [] cursor.execute(query, (session['userid'], )) for row in cursor: images.append(row) return render_template('images_list.html', title="Image List", images=images, s3_url=s3_config['url'])
def upload(): username = session.get('username') if not 'username': # check whether the user is logged in flash('Pleas log in first!', 'warning') return redirect(url_for('login')) file = request.files.get('uploadedfile') if file: filename = file.filename if filename == '': flash('Missing filename!', 'warning') return render_template("upload.html") if not allowed_file(filename): flash('Only image files allowed!', 'warning') return render_template("upload.html") else: if os.fstat(file.fileno()).st_size > 50 * 1024 * 1024: # if os.path.getsize(file.path) > 1*1024: sizeError = "The file size is larger than limit." return render_template('upload.html', sizeError=sizeError) # keys generated here # (key0: original photo/key1: text-detected photo/key2: thumbnail) key = username + '_' + filename keys = keynameFactory(key) path = os.path.join(os.getcwd(), "app", "static", "uploads") img_org = os.path.join(path, keys[0]) file.save(img_org) # Text detection img_detected = detect_text(img_org) img_thumb = cv2.resize(img_detected, None, fx=0.3, fy=0.3) # Save the detected photos to hard drive cv2.imwrite(os.path.join(path, keys[1]), img_detected) cv2.imwrite(os.path.join(path, keys[2]), img_thumb) # Write into DB cnx = get_db() cursor = cnx.cursor() query = '''INSERT INTO photos (userID, key0, key1, key2) VALUES (%s, %s, %s, %s)''' cursor.execute(query, (username, keys[0], keys[1], keys[2])) cnx.commit() flash('Photo Upload Success!', 'success') return redirect(url_for('go_album')) flash('No file selected!', 'warning') return render_template("upload.html")
def get_stats(term): """ TODO: 1 - week 0 - day """ db = get_db() if term: data = db.delay_stat_week() else: data = db.delay_stat_day() data = {k:f'{v:.2f}' for k, v in omit(data, '_id').items()} return jsonify(data)
def get_bus_num(): """ Returns number of buses that have tracked. Get {'NumOfVehicle': 21} from DB but returns {'num_of_routes': <NUMBER>} to follow same name convention """ db = get_db() result = db.get_number_of_buses() return jsonify({ 'num_of_vehicles': result.get('NumOfVehicle'), })
def deleteData(): s3 = boto3.resource('s3') bucket = s3.Bucket(s3_config['bucket']) for key in bucket.objects.all(): key.delete() query = "DELETE from images where id>0" cnx = get_db() cursor = cnx.cursor() cursor.execute(query) cnx.commit() query="ALTER TABLE images auto_increment=1" cursor.execute(query) cnx.commit() return redirect(url_for('welcome'))
def get_avg_pass(): """ Returns average number of passenagers per route. Returns { 'results': [ [ <ROUTE_NAME>, <NUMBER> ], ... ] } """ db = get_db() return jsonify({'results': db.get_avg_per_route()})
def save_new_policy(): exp_thr = request.form.get('exp_thr', type=int) shr_thr = request.form.get('shr_thr', type=int) exp_rto = request.form.get('exp_rto', type=int) shr_rto = request.form.get('shr_rto', type=int) as_period = request.form.get('as_period', type=int) as_counter = request.form.get('as_counter', type=int) error = False if exp_thr < 0 or exp_thr > 100 or \ shr_thr < 0 or shr_thr > 100 or \ shr_rto < 1 or \ exp_rto < 1 or \ as_period <= 0 or \ as_counter <= 0: error = True error_msg = "Error: One of the fields is invalid!" if error: return render_template("welcome.html", title="ManagerUI for ECE1779 Assignment 1", error_msg=error_msg) cnx = get_db() cursor = cnx.cursor() query = ''' UPDATE aspolicy set parameter_val=%s where parameter_nm=%s ''' cursor.execute(query, (exp_thr, 'exp_thr')) cnx.commit() cursor.execute(query, (shr_thr, 'shr_thr')) cnx.commit() cursor.execute(query, (shr_rto, 'shr_rto')) cnx.commit() cursor.execute(query, (exp_rto, 'exp_rto')) cnx.commit() cursor.execute(query, (as_period, 'as_period')) cnx.commit() cursor.execute(query, (as_counter, 'as_counter')) cnx.commit() return redirect(url_for('view_as_plcy'))
def signup(): if (request.method == 'GET'): return render_template("signup.html", title="Sign up") cnx = get_db() cursor = cnx.cursor() username = request.form['user'] password = request.form['psw'] query = "SELECT 1 from users where login=%s" cursor.execute(query, (username, )) row = cursor.fetchone() if row is not None: error_msg = "Error: Username already exists. Please choose a different username!" return render_template("signup.html", title="Sign up", error_msg=error_msg) query = "INSERT INTO users (login,password) VALUES (%s,%s)" cursor.execute(query, (username, password)) cnx.commit() flash("User created successfully!") return redirect(url_for('login'))
def go_album(): # Check whether the user is logged in username = session.get('username') if username is None: flash('Please log in first') return redirect(url_for('login')) else: # Show all thumbnails of the users cnx = get_db() cursor = cnx.cursor() query = 'SELECT key2 from photos WHERE userID = %s' cursor.execute(query, (username, )) thumbnails = [item[0] for item in cursor.fetchall()] urls = [] for key in thumbnails: normName = normalName(key) user_len = len(session.get('username')) normName = normName[user_len + 1:] url = url_for('static', filename='uploads/' + key) urls.append([url, key, normName]) return render_template('myalbum.html', urls=urls)
def validate_user(): cnx = get_db() cursor = cnx.cursor() username = request.form.get('user') if username != 'admin': error_msg = "Authorization Error: Only Administrators are allowed to login!" return render_template("login.html", title="Log In", error_msg=error_msg) password = request.form.get('psw') query = "SELECT id FROM users WHERE login=%s AND password=%s" cursor.execute(query, (username, password)) row = cursor.fetchone() if row is None: error_msg = "Error: Username or Password is invalid!" return render_template("login.html", title="Log In", error_msg=error_msg) session['username'] = username session['userid'] = row[0] print(session['userid']) return redirect(url_for('welcome', user=username))
def viewImage(key): cnx = get_db() cursor = cnx.cursor() query = ''' select key0, key1 from photos where key2 = %s ''' cursor.execute(query, (key, )) keys = cursor.fetchone() # Retrieve images from S3 s3 = boto3.client('s3') url0 = s3.generate_presigned_url(ClientMethod='get_object', Params={ 'Bucket': S3_BUCKET, 'Key': keys[0] }) url1 = s3.generate_presigned_url(ClientMethod='get_object', Params={ 'Bucket': S3_BUCKET, 'Key': keys[1] }) return render_template("/twoImages.html", key0=url0, key1=url1)
@staticmethod def fetch(face_collection, object_id): """ @type face_collection: Collection @type object_id: str :rtype: Person """ _id = ObjectId(object_id) result = face_collection.find_one({'_id': _id}) if result is None: return None return PersonLegacy(face_collection, result) if __name__ == "__main__": from app.utils import initialize_cf, get_db initialize_cf() db = get_db() collection = db.get_collection('new_faces') person = PersonLegacy.fetch(collection, '5b45d2af2c3fc24698f41c2f') if person.is_known: print "Person is KNOWN" if person.is_unknown: print "person is Unknown"
def get_compare_routes(): """ TODO: """ db = get_db() return jsonify({'results': list(db.compare_routes())[:100]})
def upload(): username = session.get('username') if not 'username': # check whether the user is logged in flash('Pleas log in first!', 'warning') return redirect(url_for('login')) file = request.files.get('uploadedfile') if file: filename = file.filename if filename == '': flash('Missing filename!', 'warning') return render_template("upload.html") if not allowed_file(filename): flash('Only image files allowed!', 'warning') return render_template("upload.html") else: if os.fstat(file.fileno()).st_size > 50*1024*1024: # if os.path.getsize(file.path) > 1*1024: sizeError = "The file size is larger than limit." return render_template('upload.html', sizeError=sizeError) # keys generated here # (key0: original photo/key1: text-detected photo/key2: thumbnail) key = username + '_' + filename keys = keynameFactory(key) #Connect to s3 using boto3 s3 = boto3.resource('s3') #Path to store images temporarily path = tempfile.mkdtemp() # Save original image img_org=os.path.join(path, keys[0]) file.save(img_org) with open(img_org, 'rb') as tmp: s3.Bucket(S3_BUCKET).put_object(Key=keys[0], Body=tmp) # Text detection img_detected = detect_text(img_org) img_de = os.path.join(path, keys[1]) cv2.imwrite(img_de, img_detected) #Upload the images into the S3 bucket with open(img_de, 'rb') as tmp1: s3.Bucket(S3_BUCKET).put_object(Key=keys[1], Body=tmp1) #Thumbnail creation img_thumb = cv2.resize(img_detected, None, fx=0.3, fy=0.3) img_th = os.path.join(path, keys[2]) cv2.imwrite(img_th, img_thumb) #Upload the images into the S3 bucket with open(img_th, 'rb') as tmp2: s3.Bucket(S3_BUCKET).put_object(Key=keys[2], Body=tmp2) # Write into DB cnx = get_db() cursor = cnx.cursor() query = '''INSERT INTO photos (userID, key0, key1, key2) VALUES (%s, %s, %s, %s)''' cursor.execute(query, (username, keys[0], keys[1], keys[2])) cnx.commit() flash('Photo Upload Success!', 'success') return redirect(url_for('go_album')) flash('No file selected!', 'warning') return render_template("upload.html")
def get_avg_per_stop_location(): """ TODO: """ db = get_db() return jsonify(db.avg_per_stop_location())