Snippets

Emre Şahin database api

Created by Emre Şahin last modified
  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
import sqlite3
from utils import *
import random
import cv2
import datetime as dt
import time
from collections import namedtuple

init_statements = [
    """DROP TABLE login""",
    """CREATE TABLE login (username text, password text)""",
    """INSERT INTO login (username, password) VALUES ("admin", "admin")""",
    """DROP TABLE permissions""",
    """CREATE TABLE permissions (username text, permission text)""",
    """INSERT INTO permissions (username, permission) VALUES ("admin", "training")""",
    """INSERT INTO permissions (username, permission) VALUES ("admin", "tespit")""",
    """INSERT INTO permissions (username, permission) VALUES ("admin", "video")""",
    """INSERT INTO permissions (username, permission) VALUES ("admin", "ipcamerasetting")""",
    """INSERT INTO permissions (username, permission) VALUES ("admin", "loginsetting")""",
    """DROP TABLE key_value_string""",
    """CREATE TABLE key_value_string (key text, value text)""",
    # """INSERT INTO key_value_string VALUES ("camera1.camera_id", "camera1")""",
    # """INSERT INTO key_value_string VALUES ("camera1.name", "Webcam")""",
    # """INSERT INTO key_value_string VALUES ("camera1.device", "/dev/video0")""",
    # """INSERT INTO key_value_string VALUES ("camera1.command", "")""",
    """INSERT INTO key_value_string VALUES ("camera1.camera_id", "camera1")""",
    """INSERT INTO key_value_string VALUES ("camera1.name", "IP Camera at 192.168.1.65")""",
    """INSERT INTO key_value_string VALUES ("camera1.device", "/dev/video0")""",
    """INSERT INTO key_value_string VALUES ("camera1.command", "ffmpeg -loglevel debug -rtsp_transport tcp -i rtsp://admin:euddue1967@192.168.1.65:554/live -c:v rawvideo -pix_fmt yuv420p  -f  v4l2 /dev/video0")""",
    # """INSERT INTO key_value_string VALUES ("camera2.camera_id", "camera2")""",
    # """INSERT INTO key_value_string VALUES ("camera2.name", "IP Camera at 192.168.1.67")""",
    # """INSERT INTO key_value_string VALUES ("camera2.device", "/dev/video1")""",
    # """INSERT INTO key_value_string VALUES ("camera2.command", "ffmpeg -loglevel debug -rtsp_transport tcp -i rtsp://admin:euddue1967@192.168.1.67:554/live -c:v rawvideo -pix_fmt yuv420p  -f  v4l2 /dev/video2")""",
    """INSERT INTO key_value_string VALUES ("camera2.camera_id", "camera2")""",
    """INSERT INTO key_value_string VALUES ("camera2.name", "")""",
    """INSERT INTO key_value_string VALUES ("camera2.device", "")""",
    """INSERT INTO key_value_string VALUES ("camera2.command", "")""",
    """INSERT INTO key_value_string VALUES ("camera3.camera_id", "camera3")""",
    """INSERT INTO key_value_string VALUES ("camera3.name", "")""",
    """INSERT INTO key_value_string VALUES ("camera3.device", "")""",
    """INSERT INTO key_value_string VALUES ("camera3.command", "")""",
    """INSERT INTO key_value_string VALUES ("camera4.camera_id", "camera4")""",
    """INSERT INTO key_value_string VALUES ("camera4.name", "")""",
    """INSERT INTO key_value_string VALUES ("camera4.device", "")""",
    """INSERT INTO key_value_string VALUES ("camera4.command", "")""",
    """DROP TABLE key_value_int""",
    """CREATE TABLE key_value_int (key text, value integer)""",
    """DROP TABLE person""",
    """CREATE TABLE person(id integer primary key, name text, title text, notes text)""",
    """INSERT INTO key_value_string VALUES ("history.image_store", "/home/iesahin/makimface-data/image-store")""",
    """DROP TABLE history""",
    """CREATE TABLE history(id integer primary key, camera_id integer, person_id integer, time real,
    camera_image_filename text, face_image_filename text, video_filename
    text, original_person_id integer, original_record_change_timestamp real, original_record_change_user integer)""",
]

log = init_logging()


def run_database_query(query, params):
    conn = sqlite3.connect("makimface.db")
    return conn.cursor()


def init_db():
    for s in init_statements:
        print(s)
        try:
            conn = sqlite3.connect("makimface.db")
            c = conn.cursor()
            c.execute(s)
            conn.commit()
            conn.close()
        except Exception as e:
            print(e)


def run_select_query(query, params, fetchsize=None):
    try:
        conn = sqlite3.connect("makimface.db")
        # conn.set_trace_callback(print)
        c = conn.cursor()
        c.execute(query, params)
        if fetchsize is None:
            rows = c.fetchall()
        else:
            rows = c.fetchmany(fetchsize)
        # log.debug("rows: %s", rows)
        return rows
    except Exception as e:
        log.error(e)
        return []


def run_insert_update_query(query, params):
    try:
        conn = sqlite3.connect("makimface.db")
        conn.set_trace_callback(print)
        c = conn.cursor()
        c.execute(query, params)
        conn.commit()
        last_row_id = c.lastrowid
        conn.close()
        return last_row_id
    except Exception as e:
        print(e)
        return None


def run_insert_update_many(query, params):
    try:
        conn = sqlite3.connect("makimface.db")
        conn.set_trace_callback(print)
        c = conn.cursor()
        c.executemany(query, params)
        conn.commit()
        last_row_id = c.lastrowid
        conn.close()
        return last_row_id
    except Exception as e:
        print(e)
        return None


def login(username, password):
    q = "SELECT * FROM login WHERE username=? AND password=?"
    params = (username, password)
    return run_select_query(q, params)


def permissions(username):
    q = "SELECT * FROM permissions WHERE username=?"
    params = (username, )
    return run_select_query(q, params)


def key_value_string(key):
    q = "SELECT value FROM key_value_string WHERE key=?"
    params = (key, )
    values = run_select_query(q, params)
    if len(values) > 0:
        return values[0][0]
    else:
        return None


def insert_key_value_string(key, value):
    q = "INSERT INTO key_value_string (key, value) VALUES (?, ?)"
    params = (key, value)
    return run_insert_update_query(q, params)


def update_key_value_string(key, value):
    q = "UPDATE key_value_string SET value = ? WHERE key = ?"
    params = (value, key)
    return run_insert_update_query(q, params)


def key_value_int(key):
    q = "SELECT value FROM key_value_int WHERE key=?"
    params = (key, )
    values = run_select_query(q, params)
    if len(values) > 0:
        return values[0]
    else:
        return None


def update_key_value_int(key, value):
    q = "UPDATE key_value_int set value = ? WHERE key = ?"
    params = (value, key)
    run_insert_update_query(q, params)


def key_value_string_like(key):
    q = "SELECT * FROM key_value_string WHERE key LIKE ?"
    params = (key, )
    values = run_select_query(q, params)
    return values


def insert_login(username, password):
    q = "INSERT INTO login (username, password) VALUES (?, ?)"
    params = (username, password)
    run_insert_update_query(q, params)


def insert_permissions(username, training, tespit, video, ipcamerasetting,
                       loginsetting):
    if training:
        q = "INSERT INTO permissions (username, permission) VALUES (?, \"training\")"
        params = (username, )
        run_insert_update_query(q, params)

    if tespit:
        q = "INSERT INTO permissions (username, permission) VALUES (?, \"tespit\")"
        params = (username, )
        run_insert_update_query(q, params)

    if video:
        q = "INSERT INTO permissions (username, permission) VALUES (?, \"video\")"
        params = (username, )
        run_insert_update_query(q, params)

    if ipcamerasetting:
        q = "INSERT INTO permissions (username, permission) VALUES (?, \"ipcamerasetting\")"
        params = (username, )
        run_insert_update_query(q, params)

    if loginsetting:
        q = "INSERT INTO permissions (username, permission) VALUES (?, \"loginsetting\")"
        params = (username, )
        run_insert_update_query(q, params)


def person_list():
    """Returns all person records in the dataset

    >>> pl = person_list()
    >>> pl[0]
    (1, 'firewoman', 'asude', 'avs')
    >>>
    """
    q = """SELECT * FROM person"""
    params = tuple([])
    return run_select_query(q, params)


def person_by_id(person_id):
    """Retrieves a person record by id
    >>> person_by_id(5)[0][1]
    'ceo'
    >>> person_by_id(2)[0][2]
    'affan-ali-ferzan-sahin'
    >>> person_by_id(4)[0][3]
    'hk'
    """
    log.debug(person_id)
    q = """SELECT * FROM person WHERE id=?"""
    params = (person_id, )
    res = run_select_query(q, params)
    log.debug(res)
    return res


def person_by_name_like(name):
    q = """SELECT * FROM person WHERE name LIKE ?"""
    params = ("%{}%".format(name), )
    return run_select_query(q, params)


def insert_person(title, name, notes):
    q = """INSERT INTO person (title, name, notes) VALUES (?, ?, ?)"""
    params = (title, name, notes)
    log.debug(params)
    return run_insert_update_query(q, params)


# HISTORY_IMAGE_STORE = key_value_string("history.image_store")
# if HISTORY_IMAGE_STORE is None:
#     HISTORY_IMAGE_STORE = '/tmp/makimface-cam-logs'
#     insert_key_value_string('history.image_store', HISTORY_IMAGE_STORE)

# log.debug(HISTORY_IMAGE_STORE)
# if not os.path.isdir(HISTORY_IMAGE_STORE):
#     os.makedirs(HISTORY_IMAGE_STORE)


def record_history_data(camera_id: int, person_id: int, time: float,
                        camera_image_filename: str, face_image_filename: str,
                        video_filename: str):
    if person_id is None:
        person_id = -1

    query = """INSERT INTO history(camera_id, person_id, time, camera_image_filename,
    face_image_filename, video_filename) VALUES (?, ?, ?, ?, ?, ?)"""
    params = (camera_id, person_id, time, camera_image_filename,
              face_image_filename, video_filename)

    return run_insert_update_query(query, params)


def record_multiple_history_data(record_dict: dict):
    record_list = []
    for k, v in record_dict.items():
        camera_id, person_id, camera_image, face_image, time, video_filename = v
        r = random.randint(10000, 100000)
        face_image_filename = "{}/face-{}-{}-{}-{}.png".format(
            HISTORY_IMAGE_STORE, person_id, camera_id, int(time), r)
        camera_image_filename = "{}/cam-{}-{}-{}-{}.png".format(
            HISTORY_IMAGE_STORE, camera_id, person_id, int(time), r)
        cv2.imwrite(face_image_filename, face_image)
        cv2.imwrite(camera_image_filename, camera_image)
        record_list.append((camera_id, person_id, time, camera_image_filename,
                            face_image_filename, video_filename))

    query = """INSERT INTO history(camera_id, person_id, time, camera_image_filename,
    face_image_filename, video_filename) VALUES (?, ?, ?, ?, ?, ?)"""
    return run_insert_update_many(query, record_list)


# def make_history_list(history_records):

#     history_list = []

#     for hr in history_records:
#         (rowid, camera_id, person_id, time, camera_image_filename,
#          face_image_filename, video_filename) = hr

#         person_rec = person_by_id(person_id)
#         log.debug(person_rec)
#         if len(person_rec) == 0:
#             person_name = "Unknown Unknown"
#         elif len(person_rec) == 1:
#             person_name = person_rec[0][1]
#         else:
#             log.error("More than 1 person with ID: %s", person_id)

#         # camera_key = "{}.name".format(camera_id)
#         # camera_name = key_value_string(camera_key)

#         camera_name = "Camera {}".format(camera_id)

#         if os.path.exists(camera_image_filename):
#             camera_image = cv2.imread(camera_image_filename)
#         else:
#             camera_image = None

#         if os.path.exists(face_image_filename):
#             face_image = cv2.imread(face_image_filename)
#         else:
#             face_image = None

#         history_list.append((camera_name, person_name, time, camera_image,
#                              face_image, video_filename, rowid))

#     return history_list


def make_history_list_light(history_records):

    HistoryRecord = namedtuple("HistoryRecord", [
        "row_id", "camera_id", "person_id", "time", "camera_image_filename",
        "face_image_filename", "video_filename", "person_name", "person_title",
        "person_notes"
    ])

    history_list = [HistoryRecord._make(hr) for hr in history_records]
    return history_list


def history_by_id(history_id):
    query = """
        SELECT history.id as id,
    history.camera_id as camera_id,
    history.person_id as person_id,
    history.time as time,
    history.camera_image_filename as camera_image_filename,
    history.face_image_filename as face_image_filename,
    history.video_filename as video_filename,
    person.name as person_name,
    person.title as person_title,
    person.notes as person_notes
    FROM history LEFT JOIN person ON history.person_id = person.id
    WHERE history.id = ? ;
        """
    params = (history_id, )

    results = run_select_query(query, params)
    history_list = make_history_list_light(results)
    return history_list


def history_query(person_id=None,
                  camera_id=None,
                  datetime_begin=None,
                  datetime_end=None,
                  max_elements=None):
    """General history query with multiple criteria
    WARNING! @datetime_begin @datetime_end should be in UTC.

    Args:
        person_id: ID of the person to be searched in history or None for all
    
    """
    general_query = """
        SELECT history.id as id,
    history.camera_id as camera_id,
    history.person_id as person_id,
    history.time as time,
    history.camera_image_filename as camera_image_filename,
    history.face_image_filename as face_image_filename,
    history.video_filename as video_filename,
    person.name as person_name,
    person.title as person_title,
    person.notes as person_notes
    FROM history LEFT JOIN person ON history.person_id = person.id {where_clause}
    ORDER BY time DESC {limit_clause};
        """

    criteria = []
    params = []
    if person_id is not None:
        criteria.append("history.person_id = ?")
        params.append(person_id)
    if camera_id is not None:
        criteria.append("history.camera_id = ?")
        params.append(camera_id)
    if datetime_begin is not None:
        criteria.append("history.time >= ?")
        # datetime_begin = datetime_begin.replace(
        #     tzinfo=dt.timezone.utc).timestamp()
        params.append(datetime_begin)
    if datetime_end is not None:
        criteria.append("history.time <= ?")
        # datetime_end = datetime_end.replace(tzinfo=dt.timezone.utc).timestamp()
        params.append(datetime_end)

    if len(criteria) > 0:
        where_clause = "WHERE " + " AND ".join(criteria)
        params = tuple(params)
    else:
        where_clause = ""
        params = tuple([])

    if max_elements is None:
        limit_clause = ""
    else:
        limit_clause = "LIMIT {}".format(max_elements)

    query = general_query.format(
        where_clause=where_clause, limit_clause=limit_clause)

    log.debug("query: %s", query)

    results = run_select_query(query, params)
    history_list = make_history_list_light(results)
    return history_list


def history_list(max_elements=1000):
    return history_query(max_elements=max_elements)


def history_by_person(person_id, max_elements=1000):
    return history_query(person_id=person_id, max_elements=max_elements)


def history_by_camera(camera_id, max_elements=1000):
    return history_query(camera_id=camera_id, max_elements=max_elements)


def history_by_date(begin, end, max_elements=1000):
    return history_query(
        datetime_begin=begin, datetime_end=end, max_elements=max_elements)


def history_by_unknown_persons(max_elements=1000):
    general_query = """
    SELECT id, camera_id, person_id, time, camera_image_filename, face_image_filename, video_filename
    FROM history WHERE history.person_id < 0
    ORDER BY time DESC {limit_clause};
        """
    if max_elements is None:
        limit_clause = ""
    else:
        limit_clause = "LIMIT {}".format(max_elements)

    query = general_query.format(limit_clause=limit_clause)
    params = tuple([])

    return run_select_query(query, params)


def update_history_person(rowid, current_person_id, new_person_id):
    query = """UPDATE history
    SET person_id = ? ,
    original_person_id = ? ,
    original_record_change_timestamp = ? , 
    original_record_change_user = ? 
    WHERE rowid = ?
    AND person_id = ?
    """
    ts = time.time()

    params = (new_person_id, current_person_id, ts, 0, rowid,
              current_person_id)

    return run_insert_update_query(query, params)


if __name__ == "__main__":
    import doctest
    doctest.testmod()
import sys
from os import path
import os
# print(os.environ['LD_LIBRARY_PATH'])
# print(os.environ['PATH'])

import gc

import cv2
import numpy as np
import datetime as dt
import os
import time
import io

from PySide2 import QtCore as qtc
from PySide2 import QtWidgets as qtw
from PySide2 import QtGui as qtg

import face_recognition as fr
import database_api as db

import camera_dialog as cd
import person_dialog as pd
import history_dialog as hd

import camera_controller as cc

import history_recorder
import video_recorder

import redis
import rq

from utils import *

log = init_logging()

R = redis.Redis(host='localhost', port=6379)
history_queue = rq.Queue("history", connection=R)
video_queue = rq.Queue("video", connection=R)
VIDEO_RECORD_TIMEOUT = 3600


class FaceRecognitionWidget(qtw.QWidget):
    def __init__(self, camera_controller, parent=None):
        super().__init__(parent)
        self.camera_controller = camera_controller
        self.video_device = camera_controller.device
        self.recognizer = fr.FaceRecognizer_v1()
        self.font = cv2.FONT_HERSHEY_COMPLEX_SMALL
        self.text_color = (255, 255, 0)
        self.rectangle_color = (255, 0, 255)

        self.image = qtg.QImage()
        self.timer = qtc.QBasicTimer()
        self.camera = cv2.VideoCapture(self.video_device)

    def start_timer(self):
        self.timer.start(0, self)

    def stop_timer(self):
        self.timer.stop()

    def timerEvent(self, event):
        if (event.timerId() != self.timer.timerId()):
            return

        read, image = self.camera.read()
        if read:
            self.process_image(image)

    def add_frame_to_redis(self, image_data):
        t = time.time()
        key = 'frame:{}'.format(t)
        log.debug("key: %s", key)
        filename = video_recorder.get_video_filename(
            t, self.camera_controller.camera_id)
        # memfile = io.BytesIO()
        # we can use savez here if memory becomes an issue, I prefer speed
        # np.save(memfile, image_data)
        R.hmset(
            key,
            {
                'time': t,
                'camera_id': self.camera_controller.camera_id,
                # 'image_string': memfile.getvalue(),
                'image_data': image_data.tostring(),
                'image_shape_x': image_data.shape[0],
                'image_shape_y': image_data.shape[1],
                'image_shape_z': image_data.shape[2],
                'image_dtype': image_data.dtype,
                'filename': filename
            })
        R.rpush('framekeys', key)
        log.debug("R.llen(framekeys): %s", R.llen('framekeys'))
        return filename

    def process_image(self, image_data):
        video_filename = self.add_frame_to_redis(image_data)
        faces = self.recognizer.predict_faces(image_data)
        # image_data_processed = image_data.copy()
        log.debug("faces: %s", faces)
        for coords, person_id in faces:
            log.debug(coords)
            log.debug(person_id)
            (x, y, w, h) = coords
            db_result = []
            if person_id is not None:
                person_id = int(person_id)
                db_result = db.person_by_id(person_id)
            log.debug("db_result: %s", db_result)
            if db_result == []:
                name = "Unknown Unknown"
                title = "Unknown"
                notes = ""
            else:
                assert (len(db_result) == 1)
                (person_id_, name, title, notes) = db_result[0]
            log.debug("person_id: {} title: {} name: {}".format(
                person_id, title, name))
            face_image = image_data[x:(x + w), y:(y + h)]

            history_queue.enqueue(history_recorder.record, time.time(),
                                  self.camera_controller.camera_id, person_id,
                                  image_data, face_image, video_filename)

            # SYNC CALL FOR DEBUG history_recorder.record(time.time(),
            # self.camera_controller.camera_id, person_id, image_data,
            # face_image, video_filename)

            cv2.putText(image_data, name, (y, x - 5), self.font, 1.0,
                        self.text_color, 2)
            cv2.rectangle(image_data, (y, x), (y + h, x + w),
                          self.rectangle_color, 2)
        qs = self.size()
        image_data = cv2.resize(image_data, (qs.height(), qs.width()))
        self.image = get_qimage(image_data)
        # if self.image.size() != self.size():
        #     self.setFixedSize(self.image.size())

        self.update()

    def paintEvent(self, event):
        painter = qtg.QPainter(self)
        painter.drawImage(0, 0, self.image)
        del self.image
        self.image = qtg.QImage()


class MainWidget(qtw.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.camera_controllers = cc.get_camera_controllers()
        self.camera_controllers = {
            k: c
            for k, c in self.camera_controllers.items()
            if (c.device != '' and os.path.exists(c.device))
        }

        self.run_button = qtw.QPushButton('Start')
        self.camera_configuration_button = qtw.QPushButton('Camera Config')
        self.camera_configuration_button.clicked.connect(
            self.camera_config_dialog)
        self.history_button = qtw.QPushButton('History')
        self.history_button.clicked.connect(self.history_dialog)
        self.people_button = qtw.QPushButton('People')
        self.people_button.clicked.connect(self.people_dialog)
        self.close_button = qtw.QPushButton('Close')
        self.close_button.clicked.connect(self.close)

        self.recognizers = []
        log.debug("Cameras: {}".format(self.camera_controllers))
        for cam_id, cam in self.camera_controllers.items():
            log.debug("Running for {}: {}".format(cam.name, cam.command))
            cam.run_command()
            frw = FaceRecognitionWidget(camera_controller=cam, parent=self)
            self.recognizers.append(frw)
            self.run_button.clicked.connect(frw.start_timer)

        # Connect the image data signal and slot together
        # image_data_slot = self.face_detection_widget.image_data_slot
        # self.record_video.image_data.connect(image_data_slot)
        # #
        # connect the run button to the start recording slot
        # self.run_button.clicked.connect(self.record_video.start_recording)

        # Create and set the layout

        if len(self.recognizers) == 0:
            qtw.QMessageBox.warning(self, "No Cams", "No Cameras Are Present")
            self.camera_config_dialog()
        elif len(self.recognizers) > 1:
            self.setLayout(self.layout_for_4_cameras())
        else:
            self.setLayout(self.layout_for_1_camera())

        for frw in self.recognizers:
            frw.start_timer()

    def closeEvent(self, event):
        log.debug("camera_controllers: %s", self.camera_controllers)

        for cam_id, cam in self.camera_controllers.items():
            log.debug("cam_id: %s", cam_id)
            cam.kill_command()
            log.debug("cam.process: %s", cam.process)

        for frw in self.recognizers:
            frw.stop_timer()

        log.debug("before event: %s", event)
        event.accept()
        log.debug("after event: %s", event)

    def history_dialog(self):
        history_dialog = hd.HistoryDialog(self.recognizers[0].recognizer, self)
        history_dialog.exec_()

    def camera_config_dialog(self):
        dialog = cd.CameraConfigurationDialog(self)
        dialog.exec_()

    def people_dialog(self):
        dialog = pd.PersonDialog(self.recognizers[0].recognizer, self)
        dialog.exec_()

    def layout_for_buttons(self):
        layout = qtw.QHBoxLayout()
        layout.addWidget(self.run_button, 1)
        layout.addSpacing(1)

        layout.addWidget(self.camera_configuration_button, 1)
        layout.addSpacing(1)

        layout.addWidget(self.history_button, 1)
        layout.addSpacing(1)

        layout.addWidget(self.people_button, 1)
        layout.addSpacing(1)

        layout.addWidget(self.close_button, 1)
        layout.addSpacing(1)

        return layout

    def layout_for_1_camera(self):
        layout = qtw.QVBoxLayout()
        layout.addWidget(self.recognizers[0], 2)
        layout.addLayout(self.layout_for_buttons(), 0)
        return layout

    def layout_for_4_cameras(self):
        layout = qtw.QVBoxLayout()
        camera_layout = qtw.QGridLayout()
        try:
            camera_layout.addWidget(self.recognizers[0], 0, 0, 1, 1)
            camera_layout.addWidget(self.recognizers[1], 0, 1, 1, 1)
            camera_layout.addWidget(self.recognizers[2], 1, 0, 1, 1)
            camera_layout.addWidget(self.recognizers[3], 1, 1, 1, 1)
        except IndexError:
            pass

        layout.addLayout(camera_layout, 2)
        layout.addLayout(self.layout_for_buttons(), 0)
        return layout


def main():
    app = qtw.QApplication(sys.argv)
    main_window = qtw.QMainWindow()
    main_widget = MainWidget()
    main_widget.setAttribute(qtc.Qt.WA_DeleteOnClose, True)
    main_window.setAttribute(qtc.Qt.WA_DeleteOnClose, True)
    main_window.setCentralWidget(main_widget)
    main_widget.close_button.clicked.connect(main_window.close)
    main_window.showFullScreen()
    app_return = app.exec_()
    log.debug("app_return: %s", app_return)
    return sys.exit(app_return)


if __name__ == '__main__':
    script_dir = path.dirname(path.realpath(__file__))
    # cascade_filepath = path.join(script_dir,
    #                              'haarcascade_frontalface_default.xml')

    # cascade_filepath = path.abspath(cascade_filepath)
    main()

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.