def cameras(): conn, cursor = connect() query = "SELECT title, x, y, rstp, F, current_frame FROM cameras" cursor.execute(query) cameras = cursor.fetchall() query = "SELECT * FROM occurrences WHERE DATE(`timestamp`)=CURDATE() AND e1 IS NOT NULL" cursor.execute(query) today_occurrences = cursor.fetchall() arr = [[to["e%i" % i] for i in range(1, 129)] for to in today_occurrences] arr = np.array(arr) model = OPTICS() model.fit(arr) indices = np.arange(len(today_occurrences)) result_occurrences = [] for i in range(np.max(model.labels_) + 1): person_indices = indices[model.labels_ == i] print(person_indices) if len(person_indices) < 4: continue index = np.random.choice(person_indices) result_occurrences.append('/'+'/'.join(today_occurrences[index]['human_picture'].split('/')[1:])) conn.close() print(len(result_occurrences)) return render_template('cameras.html', cameras=cameras, today_occurrences=result_occurrences)
def get_db(): try: connection = database.connect() cursor = connection.cursor(cursor_factory=PreparingCursor) return cursor, connection except Exception as exc: raise ValueError(f"{exc}")
def page(): conn, cursor = connect() query = "SELECT * FROM known_persons" cursor.execute(query) conn.close() return render_template('people.html', people=cursor.fetchall())
def delete_person(id: int): conn, cursor = connect() query = "DELETE FROM known_persons WHERE id = %s" cursor.execute(query, (id,)) conn.commit() conn.close() return redirect('/people/page')
def main_dev(): from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QMessageBox from app.ui.viewremovetablewidget import ViewRemoveTableWidget from app import database as db app = QApplication(sys.argv) widget = ViewRemoveTableWidget() widget.show() conn = db.connect(db.LOCAL) tableData = db.get_devices(conn) columnHeaders = ["Serial Number", "Description"] widget.setData(tableData, columnHeaders) @pyqtSlot(str) def on_widget_removeRow(id_): msgBox = QMessageBox() msgBox.setText(id_) msgBox.exec_() widget.removeRow.connect(on_widget_removeRow) conn.close() sys.exit(app.exec_())
def main_dev(): from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QMessageBox from app.ui.viewremovetablewidget import ViewRemoveTableWidget from app import database as db app = QApplication(sys.argv) widget = ViewRemoveTableWidget() widget.show() conn = db.connect(db.LOCAL) tableData = db.get_devices(conn) columnHeaders = ["Serial Number", "Description"] widget.setData(tableData, columnHeaders) @pyqtSlot(str) def on_widget_removeRow(id_): msgBox = QMessageBox() msgBox.setText(id_) msgBox.exec_() widget.removeRow.connect(on_widget_removeRow) conn.close() sys.exit(app.exec_())
def get_specific_person_page(id: int): conn, cursor = connect() query = "SELECT * FROM known_persons WHERE id = %s" cursor.execute(query, (id,)) person = cursor.fetchone() embedding = [value for key, value in person.items() if key.startswith('e')] string = " + ".join([f"(e{i} - {embedding[i-1]}) * (e{i} - {embedding[i-1]})" for i in range(1, 129)]) query = f"SELECT * FROM occurrences WHERE SQRT({string}) < 0.6 ORDER BY timestamp DESC" cursor.execute(query) occurrences = cursor.fetchall() conn.close() last_occurences = [occ['human_picture'] for occ in occurrences[-5:]] data = pd.DataFrame(occurrences) data.timestamp = pd.to_datetime(data['timestamp']) today = datetime.datetime.now() today_visits = data[ (data.timestamp.dt.year == today.year) & (data.timestamp.dt.month == today.month) & (data.timestamp.dt.day == today.day)] today_visits = today_visits.groupby(today_visits.timestamp.dt.hour)['id'].count() today_visits_plot = {i: 0 for i in range(24)} for i, row in today_visits.iteritems(): today_visits_plot[i] = row plt.clf() plt.xlabel('hour') plt.ylabel('number of occurrnces') plt.bar(list(today_visits_plot.keys()), list(today_visits_plot.values())) plt.savefig('123.jpg') img = plt.imread('123.jpg') success, a_numpy = cv2.imencode('.jpg', img) day_histogram = base64.b64encode(a_numpy.tobytes()).decode() this_month_visits = data[ (data.timestamp.dt.year == today.year) & (data.timestamp.dt.month == today.month)] this_month_visits = this_month_visits.groupby(this_month_visits.timestamp.dt.day)['id'].count() this_month_visits_plot = {i: 0 for i in range(30)} for i, row in this_month_visits.iteritems(): this_month_visits_plot[i] = row plt.clf() plt.bar(list(this_month_visits_plot.keys()), list(this_month_visits_plot.values())) plt.xlabel('day') plt.ylabel('number of occurrnces') plt.savefig('123.jpg') img = plt.imread('123.jpg') success, a_numpy = cv2.imencode('.jpg', img) this_month_histogram = base64.b64encode(a_numpy.tobytes()).decode() return render_template('person.html', person=person, last_occurrences=['/'+'/'.join(occ['human_picture'].split('/')[1:]) for occ in occurrences[:5]], day_histogram=day_histogram, this_month_histogram=this_month_histogram )
def make_prodigy(job_id, project_id, settings, logger, debug=False): import prodigy from app.database import connect if debug: os.environ["PRODIGY_LOGGING"] = 'basic' dbname = PRODIGY_CONFIG['db'] connect(dbname, PRODIGY_CONFIG['db_settings'][dbname]) loaded_recipe = prodigy.get_recipe(settings['recipe']) if not loaded_recipe: raise ValueError("Can't find recipe {}.".format(settings['recipe'])) args = [] # to maintaint order of arguments for item in settings['recipe_sig']: if item in settings['recipe_args']: args.append(settings['recipe_args'][item]) else: args.append(None) controller = loaded_recipe(*args) controller.config.update(PRODIGY_CONFIG) if 'config' in settings: controller.config.update(settings['config']) config = controller.config config['view_id'] = controller.view_id config['batch_size'] = controller.batch_size config['version'] = prodigy.about.__version__ if 'instructions' in settings: help_path = Path('{}/{}'.format(DATA_DIR, settings['instructions'])) if help_path.is_file(): with help_path.open('r', encoding='utf8') as f: config['instructions'] = f.read() else: config['instructions'] = settings['instructions'] for setting in ['db_settings', 'api_keys']: if setting in config: config.pop(setting) controller.save() return config, controller
def add_camera(): title = request.form.get('title') x = request.form.get('x') y = request.form.get('y') rstp = request.form.get('rstp') F = request.form.get('F') F = F if len(F) else None conn, cursor = connect() query = "INSERT INTO cameras (title, x, y, rstp, F) VALUES (%s, %s, %s, %s, %s)" cursor.execute(query, (title, x, y, rstp, F)) conn.commit() conn.close() return redirect('/cameras/page')
def add_person(): file = request.files['file'] name = request.form.get('name') image = np.array(Image.open(BytesIO(file.read()))) embedding = get_embedding(image) if embedding is not None: conn, cursor = connect() query = f"INSERT INTO known_persons (name, picture, {', '.join(['e%i' % i for i in range(1, 129)])}) "\ f"VALUES (%s, %s, {','.join(['%s' for i in range(128)])})" cursor.execute(query, (name, os.path.join('known_persons', file.filename), *embedding)) conn.commit() conn.close() plt.imsave(os.path.join('../images/known_persons', file.filename), image) return redirect("/people/page") else: return "", 400
import random import logging from hashlib import md5 from functools import wraps from pathlib import Path from flask import Flask, g, request, Response, json, render_template, send_from_directory, session, abort, flash, redirect, url_for from flask_cors import CORS, cross_origin from app.settings import * from app.database import connect, User from app.tasks import start_job, get_project, get_questions, give_answers, get_stats web = Flask(__name__) web.config.from_object(__name__) CORS(web, supports_credentials=True) DB = connect(PRODIGY_CONFIG['db'], PRODIGY_CONFIG['db_settings'][PRODIGY_CONFIG['db']]) def auth_user(user): session['logged_in'] = True session['user_id'] = user.id session['username'] = user.username flash('You are logged in as %s' % (user.username)) def get_current_user(): if session.get('logged_in'): return User.get(User.id == session['user_id']) def login_required(f):
def initialize_models(): database.connect() database.create_tables([PlainTextUpload], True) database.close()
def create_tables(): database.connect() database.create_tables([Host, CPUStats], safe=False)
from flask import Flask #init flask app app = Flask(__name__, static_folder='../../build', static_url_path='/') from app import database as db db.connect() from app import views
def create_tables(): database.connect() database.create_tables([Host, CPUStats], safe=False)
def get_all_cameras(): conn, cursor = connect() query = "SELECT title, x, y, rstp, F, current_frame FROM cameras" cursor.execute(query) conn.close() return jsonify(list(cursor.fetchall()))
def get_camera(id: int): conn, cursor = connect() query = "SELECT title, x, y, rstp, F FROM cameras WHERE id = %s" cursor.execute(query, (id,)) conn.close() return jsonify(cursor.fetchone())
def get_specific_person(id: int): conn, cursor = connect() query = "SELECT * FROM known_persons WHERE id = %s" cursor.execute(query, (id,)) conn.close() return jsonify(cursor.fetchone())
def _db_connect(): database.connect()
f = d.feed.description except AttributeError: f = '' # Almaceno el feed para el usuario en la db. feed = Feed.create(user=user, title=a, url=url, description=f) except: return render_template('newfeed.html', error_message='URL invalida') return redirect(url_for('index')) @app.route('/delete_feed/<feed>') @login_required def delete_feed(feed): # Verifico que el feed exista y elimino. Recordar que siempre los # id de los feeds no dan informacion del usuario. Por lo tanto # dos feeds iguales pero de distintos usuarios tienen distintos ids. try: feed_new = Feed.get(Feed.id == feed) except: return 'Error' feed_new.delete_instance() # Muestro el index. return redirect(url_for('index')) if __name__ == '__main__': database.connect() database.create_tables([User, Feed], safe=True) app.run()
# Do the controller import here after the models have been loaded from app.controllers import view_controller, api_controller # Some helpers to make defining the routes a bit cleaner def get(path, rule, func, *args, **kwargs): kwargs['methods'] = ['GET'] application.add_url_rule(path, rule, func, *args, **kwargs) def post(path, rule, func, *args, **kwargs): kwargs['methods'] = ['POST'] application.add_url_rule(path, rule, func, *args, **kwargs) get('/', 'index', view_controller.index) get('/upload', 'upload', view_controller.upload) get('/search', 'search', view_controller.search) post('/api/publish', 'api_publish', api_controller.publish) get('/api/search/<text>', 'api_search', api_controller.search) get('/api/search/', 'api_search_empty', api_controller.search) get('/api/get/<int:id>', 'api_get_file', api_controller.get_file) if __name__ == '__main__': application = Flask(__name__) application.json_encoder = utils.AppJsonEncoder database.connect(application) load_models() setup_routes(application) application.run(port=8000)
def get_all_persons(): conn, cursor = connect() query = "SELECT * FROM known_persons" cursor.execute(query) conn.close() return jsonify(list(cursor.fetchall()))