forked from norkator/open-intelligence
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
518 lines (421 loc) · 16.8 KB
/
database.py
File metadata and controls
518 lines (421 loc) · 16.8 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import os
import psycopg2
from argparse import ArgumentParser
# Process arguments
parser = ArgumentParser()
parser.add_argument('--bool_slave_node', type=str, help='Multi node support, give string True as input if slave.')
args = parser.parse_args()
if args.bool_slave_node == 'True':
print('[INFO] Process running in slave mode!')
params = "dbname=%s user=%s password=%s host=%s port=%s" % (
os.environ['DB_DATABASE'],
os.environ['DB_USER'],
os.environ['DB_PASSWORD'],
os.environ['DB_HOST'],
os.environ['DB_PORT']
)
# connection = psycopg2.connect(params)
# print(connection.get_backend_pid())
def db_connected():
connection = psycopg2.connect(params)
try:
cur = connection.cursor()
cur.execute('SELECT 1')
cur.close()
return True
except psycopg2.OperationalError:
return False
finally:
connection.close()
def get_application_config():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
config_query = "SELECT key, value FROM configurations"
cursor.execute(config_query)
config_records = cursor.fetchall()
cursor.close()
return config_records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def find_config_value(configs, key):
for config in configs:
if config[0] == key:
return config[1]
return None
def insert_value(name, label, file_path, file_name, year, month, day, hour, minute, second, file_name_cropped,
detection_result, color):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# Datetime format: '2011-05-16 15:36:38'
file_create_date = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
# print(file_create_date)
# Query
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
postgres_insert_query = """ INSERT INTO data (name, label, file_path, file_name, file_create_date, detection_completed, file_name_cropped, detection_result, color) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
# Variables
record_to_insert = (
name, label, file_path, file_name, file_create_date, 1, file_name_cropped, detection_result, color)
# Execute insert
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
cursor.close()
# print(count, "Database record inserted")
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def get_super_resolution_images_to_compute():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# Load specific label image not older than one day from now
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
sr_work_query = "SELECT id, label, file_name_cropped, detection_result FROM data WHERE file_create_date > now() - interval '1 day' AND (label = 'car' OR label = 'truck' OR label = 'bus') AND sr_image_computed = 0 ORDER BY id ASC LIMIT 10"
cursor.execute(sr_work_query)
sr_work_records = cursor.fetchall()
# for row in sr_work_records:
# print("Id = ", row[0], )
# print("Label = ", row[1])
# print("Cropped = ", row[2])
# print("Detection result = ", row[3], "\n")
cursor.close()
return sr_work_records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def update_super_resolution_row_result(detection_result, color, sr_image_name, id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
sr_update_query = """UPDATE data SET sr_image_computed = 1, detection_after_sr_completed = 1, detection_result = %s, color = %s, sr_image_name = %s WHERE id = %s"""
cursor.execute(sr_update_query, (detection_result, color, sr_image_name, id))
connection.commit()
cursor.close()
# count = cursor.rowcount
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def bool_run_train_face_model():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
face_action_query = "SELECT id FROM apps WHERE action_name = 'train_face_model' AND action_completed = 0 LIMIT 1"
cursor.execute(face_action_query)
face_action_query_records = cursor.fetchall()
bool_run_action = len(face_action_query_records) > 0
if bool_run_action:
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
face_action_update_query = """UPDATE apps SET action_completed = 1 WHERE action_name = 'train_face_model'"""
cursor.execute(face_action_update_query)
connection.commit()
cursor.close()
return bool_run_action
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
return False
finally:
connection.close()
def get_detection_tasks():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
detection_work_query = "SELECT id, label, file_name_cropped FROM data WHERE detection_completed = 0 AND detection_result IS NULL AND file_name_cropped IS NOT NULL ORDER BY id ASC LIMIT 10"
cursor.execute(detection_work_query)
detection_work_records = cursor.fetchall()
cursor.close()
return detection_work_records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def update_detection_task_result(id, detection_result):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
sr_update_query = """UPDATE data SET detection_completed = 1, detection_result = %s WHERE id = %s"""
cursor.execute(sr_update_query, (detection_result, id))
connection.commit()
cursor.close()
# count = cursor.rowcount
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def get_insight_face_images_to_compute():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
sr_work_query = "SELECT id, label, file_name_cropped, detection_result FROM data WHERE label = 'person' AND insight_face_computed = 0 ORDER BY id ASC LIMIT 10"
cursor.execute(sr_work_query)
sr_work_records = cursor.fetchall()
cursor.close()
return sr_work_records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def update_insight_face_as_computed(detection_result, id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
sr_update_query = """UPDATE data SET insight_face_computed = 1, detection_result = %s WHERE id = %s"""
cursor.execute(sr_update_query, (detection_result, id))
connection.commit()
cursor.close()
# count = cursor.rowcount
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def get_images_for_similarity_check_process():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
query = """SELECT id, label, file_name_cropped, file_create_date
FROM data
WHERE /*file_create_date > DATE(now()) AND*/
label in ('car', 'truck', 'bus') AND
detection_result IS NULL AND similarity_checked = 0
AND (detection_after_sr_completed = 1 OR file_create_date < DATE(now()) )
AND extract(hour from file_create_date) = (
SELECT distinct extract(hour from file_create_date)
FROM data
WHERE
/*file_create_date > DATE(now()) AND*/
label in ('car', 'truck', 'bus') AND
file_create_date < now() - interval '1 hour'
AND (detection_after_sr_completed = 1 OR file_create_date < DATE(now()) )
AND (detection_result IS NULL OR detection_result = ' ')
AND similarity_checked = 0
LIMIT 1
)
ORDER BY id ASC;"""
cursor.execute(query)
records = cursor.fetchall()
cursor.close()
return records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def update_similarity_check_row_checked(id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
update_query = """UPDATE data SET similarity_checked = 1 WHERE id = %s"""
cursor.execute(update_query, (id,))
connection.commit()
cursor.close()
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def clean_instances():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
cursor.execute("""DELETE FROM instances WHERE "updatedAt" < NOW() - interval '15 minutes'""")
connection.commit()
cursor.close()
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def new_instance(process_name):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
postgres_insert_query = """ INSERT INTO instances (process_name) VALUES (%s) RETURNING id;"""
# Execute insert
cursor.execute(postgres_insert_query, (process_name,))
inserted_id = cursor.fetchone()[0]
connection.commit()
cursor.close()
return inserted_id
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
return None
finally:
connection.close()
# noinspection PyShadowingBuiltins
def update_instance(id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
update_query = """UPDATE instances SET "updatedAt" = NOW() WHERE id = %s"""
cursor.execute(update_query, (id,))
connection.commit()
cursor.close()
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def get_labeled_for_training_lp_images():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
query = """SELECT id, label, file_name_cropped, labeling_image_x, labeling_image_y, labeling_image_x2, labeling_image_y2
FROM data WHERE labeled_for_training = 1 and (label = 'car' OR label = 'truck' or label = 'bus')
and labeling_image_x > 0
ORDER BY id ASC;"""
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
query2 = """SELECT id, NULL, file_name_cropped, labeling_image_x, labeling_image_y, labeling_image_x2, labeling_image_y2
FROM offsites WHERE labeled_for_training = 1 and (label = 'car' OR label = 'truck' or label = 'bus')
and labeling_image_x > 0
ORDER BY id ASC;"""
cursor.execute(query)
records = cursor.fetchall()
cursor.execute(query2)
records2 = cursor.fetchall()
concatenated_results = records + records2
cursor.close()
return concatenated_results
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def insert_offsite_value(name, label, file_name, year, month, day, hour, minute, second, file_name_cropped):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# Datetime format: '2011-05-16 15:36:38'
file_create_date = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
postgres_insert_query = """
INSERT INTO offsites (name, label, file_name, file_create_date, file_name_cropped) VALUES (%s,%s,%s,%s,%s) RETURNING id;
"""
# Variables
record_to_insert = (
name, label, file_name, file_create_date, file_name_cropped)
# Execute insert
cursor.execute(postgres_insert_query, record_to_insert)
inserted_id = cursor.fetchone()[0]
connection.commit()
cursor.close()
return inserted_id
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
return None
finally:
connection.close()
def get_rejected_offsite_images():
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
query = """SELECT id, file_name_cropped FROM offsites
WHERE labeled_for_training = 1 AND labeling_image_x = 0
AND labeling_image_y = 0 AND labeling_image_x2 = 0 AND labeling_image_y2 = 0;"""
cursor.execute(query)
records = cursor.fetchall()
cursor.close()
return records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def delete_rejected_offsite_image_record(id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
postgres_insert_query = """DELETE FROM offsites WHERE id = %s;"""
# Execute insert
cursor.execute(postgres_insert_query, (id,))
connection.commit()
cursor.close()
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def insert_notification(message):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# Query
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
postgres_insert_query = """INSERT INTO notifications (text) VALUES (%s)"""
# Variables
to_insert = (message,)
# Execute insert
cursor.execute(postgres_insert_query, to_insert)
connection.commit()
# count = cursor.rowcount
cursor.close()
# print(count, "Database record inserted")
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def get_data_retention_data(days):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
dr_work_query = """SELECT id, label, file_name, file_name_cropped, sr_image_name
FROM data WHERE file_create_date < now() - interval '(%s) day'
AND deleted = false ORDER BY id DESC"""
# Variables
query_params = (days,)
cursor.execute(dr_work_query, query_params)
dr_work_records = cursor.fetchall()
cursor.close()
return dr_work_records
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()
def update_data_retention_data_deleted(id):
connection = psycopg2.connect(params)
try:
cursor = connection.cursor()
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
update_query = """UPDATE data SET deleted = true WHERE id = %s"""
cursor.execute(update_query, (id,))
connection.commit()
cursor.close()
except psycopg2.DatabaseError as error:
connection.rollback()
print(error)
finally:
connection.close()