def register(): if request.method == 'GET': if session.get('logged_in'): return render_template('search.html', username=session.get('logged_in')) else: return render_template("register.html") else: # get form information username = request.form.get("username") password = request.form.get("password") rePassword = request.form.get("rePassword") if not username or not password or not rePassword: return render_template("error.html", message="Fields can't be empty!") # checks if the username exists if db.execute("SELECT * FROM users WHERE username = :username", {"username": username}).rowcount != 0: return render_template("error.html", message=username+" has already been used!") # checks if the password is correct elif password != rePassword: return render_template("error.html", message="Password doesn't match") # insert it to the database db.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username": username, "password": generate_password_hash(password)}) db.commit() return redirect(url_for('index'))
def set_frame_from_trackbar(frame): State.frame = frame db.execute("SELECT data FROM images WHERE asset_id=? AND frame=?", (ASSET_ID, State.frame)) row = db.fetchone() State.image = cv2.imdecode(np.frombuffer(row[0], np.uint8), cv2.IMREAD_UNCHANGED) State.markers = get_markers_on_frame(State.frame) State.draw_frame()
def update(self): columns = ", ".join( [column + "=?" for column in self.DB_COLUMNS.keys()]) query = "UPDATE %s SET trackable=?, %s WHERE id=?" % (self.DB_TABLE, columns) print(query) db.execute(query, (self.trackable, *self.get_db_values(), self.id)) db.commit()
def insert(self): query = "INSERT INTO %s VALUES (NULL, ?, ?, ?, ?, %s)" % ( self.DB_TABLE, ", ".join(["?"] * len(self.DB_COLUMNS.keys()))) print(query) db.execute(query, (ASSET_ID, self.frame, self.label_id, self.trackable, *self.get_db_values())) db.commit() self.id = db.lastrowid()
def addRecords(): with open('books.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) for isbn, title, author, yearPublished in tqdm(csv_reader): db.execute( "INSERT INTO books (isbn, title, author, yearPublished) VALUES (:isbn, :title, :author, :yearPublished)", { "isbn": isbn, "title": title, "author": author, "yearPublished": yearPublished }) db.commit()
def create_post(post: Post) -> DBPost: """Saves post to the database. """ insert_fields = [] placeholders = [] for f in dataclasses.fields(post): insert_fields.append(psycopg2.sql.Identifier(f.name)) placeholders.append(psycopg2.sql.Placeholder(f.name)) statement = psycopg2.sql.SQL(''' INSERT INTO posts ({insert_fields}) VALUES ({placeholders}) RETURNING {fields} ''').format( insert_fields=psycopg2.sql.SQL(',').join(insert_fields), placeholders=psycopg2.sql.SQL(',').join(placeholders), fields=DB_POST_FIELDS, ) record = db.execute( statement, params=dataclasses.asdict(post), single=True, ) return DBPost(*record)
def results(): if not session.get('logged_in'): return render_template('error.html', message="ERROR 401 Unauthorised - Please log in first!") query = request.args.get("search").lower() session['query'] = query if not query: return render_template("error.html", message="Query can't be empty!") pageNo = request.args.get("page") session['pageNo'] = pageNo if not pageNo: pageNo = 0 else: pageNo = int(pageNo) - 1 results = db.execute("SELECT isbn, title, author, yearPublished \ FROM books \ WHERE isbn LIKE :query OR \ lower(title) LIKE :query OR \ lower(author) LIKE :query", {"query": '%' + query + '%'}).fetchall() page = request.args.get(get_page_parameter(), type=int, default=1) pagination = Pagination(page = page, total = len(results), record_name='results') return render_template("results.html", query = query, results = results[(10 * pageNo):((pageNo*10)+10)], pagination = pagination, css_framework='bootstrap4')
def get_all_posts() -> typing.List[DBPost]: """Get all post from the database. """ statement = psycopg2.sql.SQL(''' SELECT {fields} FROM posts ORDER BY created_at DESC ''').format( fields=DB_POST_FIELDS, ) posts = db.execute(statement) return [DBPost(*post) for post in posts]
def remove(self): query = "DELETE FROM %s WHERE id=?" % (self.DB_TABLE, ) print(query) db.execute(query, (self.id, )) db.execute( "DELETE FROM interpolated_markers WHERE src_marker_table=? AND src_marker_id=?", (self.DB_TABLE, self.id)) db.execute( "DELETE FROM interpolated_markers WHERE dst_marker_table=? AND dst_marker_id=?", (self.DB_TABLE, self.id)) db.commit()
def api(isbn): if not isbn: return jsonify({"error" : "Bad request!"}), 400 # get book data book = db.execute("SELECT isbn, title, author, yearPublished \ FROM books \ WHERE isbn = :isbn", {"isbn": isbn}).fetchone() if not book: return jsonify({"error" : "Book not found"}), 404 # get goodread's review res = requests.get("https://www.goodreads.com/book/review_counts.json", params={"key": app.config["GOODREAD_KEY"], "isbns": isbn}).json()['books'][0] return jsonify({'title' : book.title, 'author' : book.author, 'year' : book.yearpublished, 'isbn' : book.isbn, 'review_count' : res['ratings_count'], 'average_score' : res['average_rating']}), 200
def login(): # get form information username = request.form.get("username") password = request.form.get("password") if not username or not password: return render_template("error.html", message="Fields can't be empty!") # checks if the username exists result = db.execute("SELECT id, password FROM users WHERE username = :username", {"username": username}).fetchone() # logs in the user if username exists and password is right if not result: return render_template("error.html", message="User not found! Try registering an account") elif check_password_hash(result['password'], password): session['logged_in'] = result['id'] # login_user("H") return redirect(url_for('index')) else: return render_template("error.html", message="Password doesn't match")
# Merge labels merge_labels_map = {} cur.execute("SELECT id, name FROM labels") for label in cur.fetchall(): is_new = True for current_label in LABELS: if label[1] == current_label[1]: is_new = False merge_labels_map[label[0]] = current_label[0] break if is_new: db.execute("INSERT INTO labels (name) VALUES (?)", (label[1], )) merge_labels_map[label[0]] = db.lastrowid() print("label map:", merge_labels_map) # Merge assets db.execute("SELECT id, name FROM assets") assets = db.fetchall() merge_assets_map = {} cur.execute("SELECT id, name, frame_count, width, height FROM assets") for asset in cur.fetchall(): is_new = True for current_asset in assets:
def get_uptimez() -> typing.Any: """Polled by uptime monitor to check that the system is alive. """ db.execute('SELECT 1') return {'status': 'OK'}
# Constants PRETRAINED_MODELS_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "pretrained_models")) PRETRAINED_MODEL_PATH = os.path.join(PRETRAINED_MODELS_PATH, "ssd_mobilenet_v1_quantized") PRETRAINED_MODEL_CKPT = os.path.join(PRETRAINED_MODEL_PATH, "model.ckpt") LABEL_MAP_PATH = os.path.join(OUTPUT_DIRECTORY, "label_map.pbtxt") LABEL_TXT_PATH = os.path.join(OUTPUT_DIRECTORY, "labels.txt") TEST_RECORD_PATH = os.path.join(OUTPUT_DIRECTORY, "test.record") TRAIN_RECORD_PATH = os.path.join(OUTPUT_DIRECTORY, "train.record") # Get labels label_names = {} only_labels = args.only.split(",") db.execute("SELECT id, name FROM labels") for row in db.fetchall(): if args.only == "ALL" or row[1] in only_labels: print(row) label_names[row[0]] = row[1] # Generate TF records test_writer = tf.io.TFRecordWriter(TEST_RECORD_PATH) train_writer = tf.io.TFRecordWriter(TRAIN_RECORD_PATH) db.execute("SELECT id, name, frame_count, width, height FROM assets") assets = db.fetchall() used_label_ids = [] test_set_size = 0
# Constants MODEL_PATH = os.path.join(OUTPUT_DIRECTORY, "detect.tflite") # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpreter(model_path=MODEL_PATH) interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Play video cv2.namedWindow(WINDOW_NAME) for frame in range(FRAME_COUNT): db.execute("SELECT data FROM images WHERE asset_id=? AND frame=?", (ASSET_ID, frame)) row = db.fetchone() image = cv2.imdecode(np.frombuffer(row[0], np.uint8), cv2.IMREAD_UNCHANGED) image_input = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_input = cv2.resize(image, (300, 300)) image_input = image_input.reshape(1, *image_input.shape) image_input = image_input.astype(np.uint8) interpreter.set_tensor(input_details[0]["index"], image_input) interpreter.invoke() boxes = interpreter.get_tensor(output_details[0]["index"]) labels = interpreter.get_tensor(output_details[1]["index"]) scores = interpreter.get_tensor(output_details[2]["index"]) num = interpreter.get_tensor(output_details[3]["index"])
USED_LABELS = filter(lambda label: label != "NO_LABEL", args.labels.split(",")) LABEL_DISPLAY_HEIGHT = 30 COLORS = ((164, 0, 0), (0, 164, 0), (0, 0, 164), (164, 164, 0), (0, 164, 164), (164, 0, 164), (200, 100, 0), (0, 100, 200), (100, 200, 0)) try: os.makedirs(OUTPUT_DIRECTORY) except FileExistsError: pass # Open database db.connect(DB_PATH) #db.execute("DROP TABLE labels") db.execute( "CREATE TABLE IF NOT EXISTS labels (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)" ) #db.execute("DROP TABLE assets") db.execute( "CREATE TABLE IF NOT EXISTS assets (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, frame_count INTEGER, width INTEGER, height INTEGER)" ) #db.execute("DROP TABLE images") db.execute( "CREATE TABLE IF NOT EXISTS images (asset_id INTEGER, frame INTEGER, data BLOB)" ) db.commit() # Prepare labels for label_name in USED_LABELS: try:
def deleteRecords(): db.execute("DELETE FROM books") db.commit()
def result(): if not session.get('logged_in'): return render_template('error.html', message="ERROR 401 Unauthorised - Please log in first!") # retrieve old reviews if request.method == 'GET': isbn = request.args.get("search") if not isbn: return render_template('error.html', message="GET Query not found!") # get book data book = db.execute("SELECT isbn, title, author, yearPublished \ FROM books \ WHERE isbn = :isbn", {"isbn": isbn}).fetchone() # get user's review review = db.execute("SELECT review, star \ FROM reviews \ WHERE id = :id AND isbn = :isbn", {"id" : session.get('logged_in'), "isbn" : isbn}).fetchone() # get all reviews reviews = db.execute("SELECT * \ FROM reviews \ WHERE isbn = :isbn", {"isbn" : isbn}).fetchall() if not book: return render_template("error.html", message = "Book not found!") # get goodread's review res = requests.get("https://www.goodreads.com/book/review_counts.json", params={"key": os.environ.get("GOODREAD_KEY"), "isbns": isbn}).json()['books'][0] if res: rating_count = res['ratings_count'] avg_rating = res['average_rating'] return render_template("result.html", book = book, review = review, reviews = reviews, rating_count = rating_count, avg_rating = avg_rating, starDesc = zip(starRating, starValue, starSize, starTitle)) # if user wants to add a new review else: # retrieve info from forms rating = request.form.get("rating") review = request.form.get("review") isbn = request.form.get("search") currentTime = time.time() ts = datetime.datetime.fromtimestamp(currentTime).strftime('%Y-%m-%d %H:%M:%S') username = db.execute("SELECT username FROM users WHERE id = :id", {"id" : session.get('logged_in')}).fetchone()[0] if not rating: return render_template("error.html", message="Rating can't be empty!") elif not review: return render_template("error.html", message="Review field can't be empty!") # insert it to the database db.execute("INSERT INTO reviews (id, username, isbn, star, review, review_timestamp) \ VALUES (:id, :username, :isbn, :star, :review, :ts)", {"id": session.get('logged_in'), "username": username, "isbn": isbn, "star": rating, "review": review, "ts": ts}) db.commit() return redirect(url_for('results', search=session['query'], page=session['pageNo']))
def delete(): db.execute("DELETE FROM users") db.commit() return redirect(url_for('index'))
import cv2 import os import numpy as np from src import db from src.mode.default_mode import DefaultMode from src.mode.create_marker_mode import CreateMarkerMode from src.mode.resize_marker_mode import ResizeMarkerMode from src.mode.track_mode import TrackMode from src.marker.marker_db import delete_markers_by_clause from src import * db.execute("DELETE FROM assets WHERE id=?", (ASSET_ID, )) db.execute("DELETE FROM images WHERE asset_id=?", (ASSET_ID, )) delete_markers_by_clause("WHERE asset_id=?", (ASSET_ID, )) db.commit() db.close()