forked from rosteleset/falprs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlprs_workflow.cpp
More file actions
1958 lines (1742 loc) · 83.8 KB
/
lprs_workflow.cpp
File metadata and controls
1958 lines (1742 loc) · 83.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cmath>
#include <filesystem>
#include <absl/strings/str_format.h>
#include <absl/strings/substitute.h>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <http_client.h>
#include <userver/engine/sleep.hpp>
#include <userver/engine/wait_all_checked.hpp>
#include <userver/fs/write.hpp>
#include <userver/http/common_headers.hpp>
#include <userver/http/content_type.hpp>
#include <userver/yaml_config/merge_schemas.hpp>
#include "lprs_api.hpp"
#include "lprs_workflow.hpp"
namespace tc = triton::client;
namespace Lprs
{
inline bool cmp_vehicles(const Vehicle& a, const Vehicle& b)
{
return a.confidence > b.confidence;
}
inline bool cmp_plates(const LicensePlate& a, const LicensePlate& b)
{
return a.confidence > b.confidence;
}
inline bool hasIntersection(float lbox[4], float rbox[4])
{
const float inter_box[] =
{
std::max(lbox[0], rbox[0]), // left
std::min(lbox[2], rbox[2]), // right
std::max(lbox[1], rbox[1]), // top
std::min(lbox[3], rbox[3]), // bottom
};
return inter_box[0] < inter_box[1] && inter_box[2] < inter_box[3];
}
inline float iou(const cv::Rect2f& r1, const cv::Rect2f& r2)
{
const auto r_intersection = r1 & r2;
return r_intersection.area() / (r1.area() + r2.area() - r_intersection.area());
}
// non-maximum suppression algorithm for vehicle detection
inline void nms_vehicles(std::vector<Vehicle>& vehicles, const float threshold)
{
std::ranges::sort(vehicles, cmp_vehicles);
for (size_t m = 0; m < vehicles.size(); ++m)
{
auto& [bbox, confidence, is_special, license_plates] = vehicles[m];
for (size_t n = m + 1; n < vehicles.size(); ++n)
{
auto r1 = cv::Rect2f(cv::Point2f{bbox[0], bbox[1]}, cv::Point2f{bbox[2], bbox[3]});
if (auto r2 = cv::Rect2f(cv::Point2f{vehicles[n].bbox[0], vehicles[n].bbox[1]}, cv::Point2f{vehicles[n].bbox[2], vehicles[n].bbox[3]}); iou(r1, r2) > threshold)
{
vehicles.erase(vehicles.begin() + static_cast<int>(n));
--n;
}
}
}
}
// non-maximum suppression algorithm for plate detection
inline void nms_plates(std::vector<LicensePlate>& dets)
{
std::ranges::sort(dets, cmp_plates);
for (size_t m = 0; m < dets.size(); ++m)
{
auto& [bbox, confidence, kpts, plate_class, plate_numbers] = dets[m];
for (size_t n = m + 1; n < dets.size(); ++n)
{
if (plate_class == dets[n].plate_class && hasIntersection(bbox, dets[n].bbox))
{
dets.erase(dets.begin() + static_cast<int>(n));
--n;
}
}
}
}
inline bool cmp_chars_conf(const CharData& a, const CharData& b)
{
return a.confidence > b.confidence;
}
inline bool cmp_chars_position(const CharData& a, const CharData& b)
{
constexpr int32_t xmin = 0;
// single line license plate number
if (a.plate_class == PLATE_CLASS_RU_1)
return a.bbox[xmin] < b.bbox[xmin];
// double line license plate number
if (a.plate_class == PLATE_CLASS_RU_1A)
{
constexpr int32_t ymin = 1;
constexpr int32_t ymax = 3;
if (a.bbox[ymax] < b.bbox[ymin])
return true;
if (a.bbox[ymin] > b.bbox[ymax])
return false;
const auto y = a.bbox[ymin] + 0.5 * (a.bbox[ymax] - a.bbox[ymin]);
if (y < b.bbox[ymin])
return true;
if (y > b.bbox[ymax])
return false;
}
return a.bbox[xmin] < b.bbox[xmin];
}
// non-maximum suppression algorithm for char recognition
inline void nms_chars(std::vector<CharData>& chars, const float threshold)
{
std::ranges::sort(chars, cmp_chars_conf);
for (size_t m = 0; m < chars.size(); ++m)
{
auto& [bbox, confidence, char_class, plate_class] = chars[m];
for (size_t n = m + 1; n < chars.size(); ++n)
{
auto r1 = cv::Rect2f(cv::Point2f{bbox[0], bbox[1]}, cv::Point2f{bbox[2], bbox[3]});
if (auto r2 = cv::Rect2f(cv::Point2f{chars[n].bbox[0], chars[n].bbox[1]}, cv::Point2f{chars[n].bbox[2], chars[n].bbox[3]}); char_class == chars[n].char_class && iou(r1, r2) > threshold)
{
chars.erase(chars.begin() + static_cast<int>(n));
--n;
}
}
}
}
inline float euclidean_distance(const float x1, const float y1, const float x2, const float y2)
{
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
inline std::vector<float> softMax(const std::vector<float>& v)
{
if (v.empty())
return {};
std::vector<float> r(v.size());
float s = 0.0f;
for (const float i : v)
s += exp(i);
for (size_t i = 0; i < v.size(); ++i)
r[i] = exp(v[i]) / s;
return r;
}
inline std::vector<std::vector<cv::Point>> convertToAbsolute(const std::vector<std::vector<cv::Point2f>>& work_area, int32_t width, int32_t height)
{
std::vector<std::vector<cv::Point>> wa(work_area.size());
for (size_t i = 0; i < work_area.size(); ++i)
{
wa[i].reserve(work_area[i].size());
for (size_t j = 0; j < work_area[i].size(); ++j)
wa[i].emplace_back(static_cast<int>(work_area[i][j].x * width / 100.0f), static_cast<int>(work_area[i][j].y * height / 100.0f));
}
return wa;
}
Workflow::Workflow(const userver::components::ComponentConfig& config,
const userver::components::ComponentContext& context)
: LoggableComponentBase{config, context},
task_processor_(context.GetTaskProcessor(config["task_processor"].As<std::string>())),
fs_task_processor_(context.GetTaskProcessor(config["fs-task-processor"].As<std::string>())),
http_client_(context.FindComponent<userver::components::HttpClient>().GetHttpClient()),
vstreams_config_cache_(context.FindComponent<VStreamsConfigCache>()),
pg_cluster_(context.FindComponent<userver::components::Postgres>(kDatabase).GetCluster()),
logger_(context.FindComponent<userver::components::Logging>().GetLogger(std::string(kLogger)))
{
local_config_.allow_group_id_without_auth = config[ConfigParams::SECTION_NAME][ConfigParams::ALLOW_GROUP_ID_WITHOUT_AUTH].As<decltype(local_config_.allow_group_id_without_auth)>();
local_config_.ban_maintenance_interval = config[ConfigParams::SECTION_NAME][ConfigParams::BAN_MAINTENANCE_INTERVAL].As<decltype(local_config_.ban_maintenance_interval)>();
local_config_.events_log_maintenance_interval = config[ConfigParams::SECTION_NAME][ConfigParams::EVENTS_LOG_MAINTENANCE_INTERVAL].As<decltype(local_config_.events_log_maintenance_interval)>();
local_config_.events_log_ttl = config[ConfigParams::SECTION_NAME][ConfigParams::EVENTS_LOG_TTL].As<decltype(local_config_.events_log_ttl)>();
local_config_.events_screenshots_path = config[ConfigParams::SECTION_NAME][ConfigParams::EVENTS_SCREENSHOTS_PATH].As<decltype(local_config_.events_screenshots_path)>();
if (!local_config_.events_screenshots_path.empty() && !local_config_.events_screenshots_path.ends_with("/"))
local_config_.events_screenshots_path += "/";
local_config_.events_screenshots_url_prefix = config[ConfigParams::SECTION_NAME][ConfigParams::EVENTS_SCREENSHOTS_URL_PREFIX].As<decltype(local_config_.events_screenshots_url_prefix)>();
if (!local_config_.events_screenshots_url_prefix.empty() && !local_config_.events_screenshots_url_prefix.ends_with("/"))
local_config_.events_screenshots_url_prefix += "/";
local_config_.failed_path = config[ConfigParams::SECTION_NAME][ConfigParams::FAILED_PATH].As<decltype(local_config_.failed_path)>();
if (!local_config_.failed_path.empty() && !local_config_.failed_path.ends_with("/"))
local_config_.failed_path += "/";
local_config_.failed_ttl = config[ConfigParams::SECTION_NAME][ConfigParams::FAILED_TTL].As<decltype(local_config_.failed_ttl)>();
if (local_config_.ban_maintenance_interval.count() > 0)
ban_maintenance_task_.Start(kBanMaintenanceName,
{std::chrono::milliseconds(local_config_.ban_maintenance_interval),
{userver::utils::PeriodicTask::Flags::kStrong}},
[this]
{ doBanMaintenance(); });
if (local_config_.events_log_maintenance_interval.count() > 0)
events_log_maintenance_task_.Start(kEventsLogMaintenanceName,
{std::chrono::milliseconds(local_config_.events_log_maintenance_interval),
{userver::utils::PeriodicTask::Flags::kStrong}},
[this]
{ doEventsLogMaintenance(); });
}
userver::yaml_config::Schema Workflow::GetStaticConfigSchema()
{
return userver::yaml_config::MergeSchemas<LoggableComponentBase>(R"~(
# yaml
type: object
description: Component for license plate recognition workflow
additionalProperties: false
properties:
task_processor:
type: string
description: main task processor for recognition workflow
fs-task-processor:
type: string
description: task processor to process filesystem bound tasks
config:
type: object
description: default configuration parameters
additionalProperties: false
properties:
allow-group-id-without-auth:
type: number
description: Allow use of a group with a specified identifier without authorization
defaultDescription: 1
ban-maintenance-interval:
type: string
description: Interval in for ban maintenance
defaultDescription: 5s
events-log-maintenance-interval:
type: string
description: Interval for events log maintenance
defaultDescription: 2h
events-log-ttl:
type: string
description: Time to live for events log
defaultDescription: 4h
screenshots-path:
type: string
description: Local path for saving event screenshots
defaultDescription: '/opt/falprs/static/frs/screenshots/'
screenshots-url-prefix:
type: string
description: Web URL prefix for events' screenshots
defaultDescription: 'http://localhost:9051/lprs/'
failed-path:
type: string
description: Local path for saving unrecognized license plates screenshots
defaultDescription: '/opt/falprs/static/lprs/failed/'
failed-ttl:
type: string
description: Time to live for the unrecognized license plates screenshots
defaultDescription: 60d
)~");
}
void Workflow::startWorkflow(std::string&& vstream_key)
{
std::chrono::milliseconds workflow_timeout{std::chrono::seconds{0}};
// scope for accessing cache
{
const auto cache = vstreams_config_cache_.Get();
if (!cache->getData().contains(vstream_key))
return;
workflow_timeout = cache->getData().at(vstream_key).workflow_timeout;
}
bool do_pipeline = false;
// scope for accessing concurrent variable
{
auto data_ptr = being_processed_vstreams.Lock();
if (!data_ptr->contains(vstream_key))
do_pipeline = true;
(*data_ptr)[vstream_key] = true;
}
if (workflow_timeout.count() > 0)
{
auto data_ptr = vstream_timeouts.Lock();
(*data_ptr)[vstream_key] = std::chrono::steady_clock::now() + workflow_timeout;
}
if (do_pipeline)
tasks_.Detach(AsyncNoSpan(task_processor_, &Workflow::processPipeline, this, std::move(vstream_key)));
}
void Workflow::stopWorkflow(std::string&& vstream_key, const bool is_internal)
{
// scope for accessing concurrent variable
{
auto data_ptr = being_processed_vstreams.Lock();
if (data_ptr->contains(vstream_key))
{
if (is_internal)
data_ptr->erase(vstream_key);
else
(*data_ptr)[vstream_key] = false;
}
}
// scope for accessing concurrent variable
{
auto data_ptr = vstream_timeouts.Lock();
if (data_ptr->contains(vstream_key))
data_ptr->erase(vstream_key);
}
}
const LocalConfig& Workflow::getLocalConfig()
{
return local_config_;
}
const userver::logging::LoggerPtr& Workflow::getLogger()
{
return logger_;
}
// private methods
void Workflow::OnAllComponentsAreStopping()
{
tasks_.CancelAndWait();
}
void Workflow::processPipeline(std::string&& vstream_key)
{
VStreamConfig config;
// scope for accessing cache
{
auto cache = vstreams_config_cache_.Get();
if (!cache->getData().contains(vstream_key))
{
stopWorkflow(std::move(vstream_key));
return;
}
config = cache->getData().at(vstream_key);
}
if (config.screenshot_url.empty())
{
stopWorkflow(std::move(vstream_key));
return;
}
if (config.logs_level <= userver::logging::Level::kDebug)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kDebug,
"Start processPipeline: vstream_key = {}; frame_url = {}",
vstream_key, config.screenshot_url);
try
{
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before image acquisition",
vstream_key);
// parse user and password
std::string auth_user;
std::string auth_password;
if (auto char_alpha = config.screenshot_url.find('@'); char_alpha != std::string::npos)
{
if (auto protocol_suffix = config.screenshot_url.find("://"); protocol_suffix != std::string::npos && protocol_suffix < char_alpha)
{
if (auto char_colon = config.screenshot_url.find(':', protocol_suffix + 3); char_colon != std::string::npos && char_colon < char_alpha)
{
auto char_slash = protocol_suffix + 2;
auth_user = config.screenshot_url.substr(char_slash + 1, char_colon - char_slash - 1);
auth_password = config.screenshot_url.substr(char_colon + 1, char_alpha - char_colon - 1);
}
}
}
// clang-format off
auto capture_response = http_client_.CreateRequest()
.get(config.screenshot_url)
.http_auth_type(userver::clients::http::HttpAuthType::kAnySafe, false, auth_user, auth_password)
.retry(config.max_capture_error_count)
.timeout(config.capture_timeout)
.perform();
// clang-format on
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after image acquisition",
vstream_key);
if (capture_response->status_code() != userver::clients::http::Status::OK || capture_response->body_view().empty())
{
if (config.logs_level <= userver::logging::Level::kError)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kError,
"vstream_key = {}; url = {}; status_code = {}",
vstream_key, config.screenshot_url, capture_response->status_code());
if (config.delay_after_error.count() > 0)
{
if (config.logs_level <= userver::logging::Level::kError)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kError,
"vstream_key = {}; delay for {}ms",
vstream_key, config.delay_after_error.count());
nextPipeline(std::move(vstream_key), config.delay_after_error);
} else
stopWorkflow(std::move(vstream_key));
return;
}
if (config.logs_level <= userver::logging::Level::kTrace)
{
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; image size = {} bytes",
vstream_key, capture_response->body_view().size());
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before decoding the image",
vstream_key);
}
cv::Mat frame = imdecode(std::vector<char>(capture_response->body_view().begin(), capture_response->body_view().end()),
cv::IMREAD_COLOR);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after decoding the image",
vstream_key);
// for test: rotate image
/*float angle = -12.0f;
cv::Point2f p_center((frame.cols - 1) / 2.0f, (frame.rows - 1) / 2.0f);
cv::Mat m_rotation = cv::getRotationMatrix2D(p_center, angle, 1.0);
cv::warpAffine(frame, frame, m_rotation, frame.size());
cv::imwrite("test.jpg", frame); */
// cv::Mat frame = cv::imread("2023-05-16_17_43_57.png", cv::IMREAD_COLOR);
// cv::Mat frame = cv::imread("ru002.jpg", cv::IMREAD_COLOR);
std::vector<Vehicle> detected_vehicles;
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before doInferenceVdNet",
vstream_key);
doInferenceVdNet(frame, config, detected_vehicles);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after doInferenceVdNet",
vstream_key);
if (config.flag_process_special)
{
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before doInferenceVcNet",
vstream_key);
doInferenceVcNet(frame, config, detected_vehicles);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after doInferenceVcNet",
vstream_key);
}
if (config.logs_level <= userver::logging::Level::kTrace)
for (size_t i = 0; i < detected_vehicles.size(); ++i)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; vehicle {} confidence: {:.3f}",
vstream_key, i, detected_vehicles[i].confidence);
// check for special vehicles ban
bool is_special_banned = false;
{
auto ban_special_data_ptr = ban_special_data.Lock();
if (ban_special_data_ptr->contains(vstream_key))
{
auto now = std::chrono::steady_clock::now();
is_special_banned = (*ban_special_data_ptr)[vstream_key] > now;
if (is_special_banned)
{
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; special vehicles are banned ({}s left)",
vstream_key, std::chrono::duration_cast<std::chrono::seconds>((*ban_special_data_ptr)[vstream_key] - now).count());
} else
{
ban_special_data_ptr->erase(vstream_key);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; special vehicles are no longer banned",
vstream_key);
}
}
}
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before doInferenceLpdNet",
vstream_key);
doInferenceLpdNet(frame, config, detected_vehicles);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after doInferenceLpdNet",
vstream_key);
removeDuplicatePlates(config, detected_vehicles, frame.cols, frame.rows);
// for test
// save images of the special vehicles
/*for (size_t v = 0; v < detected_vehicles.size(); ++v)
if (detected_vehicles[v].is_special)
{
cv::Rect roi(cv::Point{static_cast<int>(detected_vehicles[v].bbox[0]), static_cast<int>(detected_vehicles[v].bbox[1])},
cv::Point{static_cast<int>(detected_vehicles[v].bbox[2]), static_cast<int>(detected_vehicles[v].bbox[3])});
imwrite(absl::Substitute("special_$0_$1.jpg", config.id_vstream, v), frame(roi));
}*/
std::vector<LicensePlate*> detected_plates;
for (const auto& [bbox, confidence, is_special, license_plates] : detected_vehicles)
for (const auto& license_plate : license_plates)
detected_plates.push_back(const_cast<LicensePlate*>(&license_plate));
bool result = true;
if (!detected_plates.empty())
{
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; before doInferenceLprNet",
vstream_key);
result = doInferenceLprNet(frame, config, detected_plates);
if (config.logs_level <= userver::logging::Level::kTrace)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kTrace,
"vstream_key = {}; after doInferenceLprNet",
vstream_key);
}
if (result)
{
auto now = std::chrono::steady_clock::now();
userver::formats::json::ValueBuilder json_data;
userver::formats::json::ValueBuilder callback_info;
bool has_special = false;
bool has_failed = false;
for (const auto& [bbox, confidence, is_special, license_plates] : detected_vehicles)
{
userver::formats::json::ValueBuilder vehicle_data;
has_special = has_special || is_special;
for (const auto& [bbox, confidence, kpts, plate_class, plate_numbers] : license_plates)
{
has_failed = has_failed || plate_numbers.empty();
for (const auto& [number, score] : plate_numbers)
{
auto k = absl::StrCat(vstream_key, "_", number);
// Description of the two-stage ban.
// If the system sees the number for the first time, then after processing it will fall into the first stage of the ban.
// At the first stage of the ban, the number is ignored regardless of its location in the frame.
// After some time (config ban-duration), the number falls into the second stage of the ban.
// At the second stage of the ban (config ban-duration-area), the number is also ignored until it changes its location in the frame.
// If at the second stage of the ban the number changes its location (config ban-iou-threshold), it will be processed and will again be included in the first stage.
if (config.ban_duration.count() > 0 && config.ban_duration_area.count() > 0)
{
bool is_banned = false;
auto banned_tp1 = now + config.ban_duration;
auto banned_tp2 = now + config.ban_duration_area;
auto banned_bbox = cv::Rect2f(cv::Point2f{bbox[0], bbox[1]}, cv::Point2f{bbox[2], bbox[3]});
auto data_ptr = ban_data.Lock();
if (data_ptr->contains(k))
{
is_banned = (*data_ptr)[k].tp1 > now;
if (is_banned)
{
if (config.logs_level <= userver::logging::Level::kDebug)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kDebug,
"vstream_key = {}; plate number {} is banned at the first stage ({}s left)",
vstream_key, number, std::chrono::duration_cast<std::chrono::seconds>((*data_ptr)[k].tp1 - now).count());
} else
{
// check area ban
auto iou_value = iou(banned_bbox, (*data_ptr)[k].bbox);
is_banned = iou_value > config.ban_iou_threshold;
if (is_banned)
{
// extending the second stage of the ban
banned_bbox = (*data_ptr)[k].bbox;
banned_tp1 = (*data_ptr)[k].tp1;
}
if (config.logs_level <= userver::logging::Level::kDebug)
{
if (is_banned)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kDebug,
"vstream_key = {}; plate_number {} is banned at the second stage (iou = {:.2f}, threshold = {:.2f})",
vstream_key, number, iou_value, config.ban_iou_threshold);
else
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kDebug,
"vstream_key = {}; plate_numbers {} was removed from the the second stage ban (iou = {:.2f}, threshold = {:.2f})",
vstream_key, number, iou_value, config.ban_iou_threshold);
}
}
}
// update ban data
(*data_ptr)[k] = {banned_tp1, banned_tp2, banned_bbox};
if (is_banned)
continue;
}
if (config.logs_level <= userver::logging::Level::kInfo)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kInfo,
"vstream_key = {}; plate number: {}",
vstream_key, number);
userver::formats::json::ValueBuilder plate_data;
plate_data[Api::PARAM_BOX] = userver::formats::json::MakeArray(
static_cast<int32_t>(bbox[0]),
static_cast<int32_t>(bbox[1]),
static_cast<int32_t>(bbox[2]),
static_cast<int32_t>(bbox[3]));
plate_data[Api::PARAM_KPTS] = userver::formats::json::MakeArray(
static_cast<int32_t>(kpts[0]),
static_cast<int32_t>(kpts[1]),
static_cast<int32_t>(kpts[2]),
static_cast<int32_t>(kpts[3]),
static_cast<int32_t>(kpts[4]),
static_cast<int32_t>(kpts[5]),
static_cast<int32_t>(kpts[6]),
static_cast<int32_t>(kpts[7]));
plate_data[Api::PARAM_NUMBER] = number;
plate_data[Api::PARAM_SCORE] = score;
plate_data[Api::PARAM_PLATE_TYPE] = PLATE_CLASSES[plate_class];
vehicle_data[Api::PARAM_PLATES_INFO].PushBack(std::move(plate_data));
userver::formats::json::ValueBuilder plate_data_short;
plate_data_short[Api::PARAM_PLATE_TYPE] = PLATE_CLASSES[plate_class];
plate_data_short[Api::PARAM_NUMBER] = number;
callback_info.PushBack(std::move(plate_data_short));
}
}
if (!vehicle_data.IsEmpty() || (is_special && !is_special_banned))
{
vehicle_data[Api::PARAM_IS_SPECIAL] = is_special;
vehicle_data[Api::PARAM_CONFIDENCE] = confidence;
vehicle_data[Api::PARAM_BOX] = userver::formats::json::MakeArray(static_cast<int32_t>(bbox[0]),
static_cast<int32_t>(bbox[1]),
static_cast<int32_t>(bbox[2]),
static_cast<int32_t>(bbox[3]));
json_data[Api::PARAM_VEHICLES_INFO].PushBack(std::move(vehicle_data));
}
}
if (!json_data.IsEmpty())
{
auto t_now = std::chrono::system_clock::now();
auto log_date = userver::storages::postgres::TimePointTz{t_now};
auto uuid = boost::uuids::to_string(boost::uuids::random_generator()());
auto path_suffix = absl::Substitute("$0/$1/$2/$3/", uuid[0], uuid[1], uuid[2], uuid[3]);
auto screenshot_extension = ".jpg";
json_data[Api::PARAM_SCREENSHOT_URL] = absl::StrCat(local_config_.events_screenshots_url_prefix, path_suffix,
uuid, screenshot_extension);
json_data[Api::PARAM_EVENT_DATE] = log_date;
auto id_event = addEventLog(config.id_vstream, log_date, json_data.ExtractValue());
// write screenshot to a file
auto path_prefix = absl::StrCat(local_config_.events_screenshots_path, path_suffix);
userver::fs::CreateDirectories(fs_task_processor_, path_prefix);
auto path = absl::StrCat(path_prefix, uuid, screenshot_extension);
userver::fs::RewriteFileContents(fs_task_processor_, path, capture_response->body_view());
userver::fs::Chmod(fs_task_processor_, path,
boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write | boost::filesystem::perms::others_read | boost::filesystem::perms::others_write);
// send data to callback
userver::formats::json::ValueBuilder json_callback;
json_callback[Api::PARAM_STREAM_ID] = config.ext_id;
json_callback[Api::PARAM_EVENT_DATE] = log_date;
json_callback[Api::PARAM_EVENT_ID] = id_event;
if (!callback_info.IsNull())
json_callback[Api::PARAM_PLATES_INFO] = callback_info;
json_callback[Api::PARAM_HAS_SPECIAL] = has_special;
try
{
// clang-format off
auto response = http_client_.CreateRequest()
.post(config.callback_url)
.headers({{userver::http::headers::kContentType, userver::http::content_type::kApplicationJson.ToString()}})
.data(userver::formats::json::ToString(json_callback.ExtractValue()))
.timeout(config.callback_timeout)
.perform();
// clang-format on
if (!(response->status_code() == userver::clients::http::Status::OK
|| response->status_code() == userver::clients::http::Status::NoContent))
if (config.logs_level <= userver::logging::Level::kWarning)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kWarning,
"vstream_key = {}; error sending data to callback {}",
vstream_key, config.callback_url);
} catch (std::exception& e)
{
LOG_ERROR_TO(logger_,
"vstream_key = {}; error sending data to callback {}; {}",
vstream_key, config.callback_url, e.what());
}
}
if (has_special)
{
auto ban_special_data_ptr = ban_special_data.Lock();
(*ban_special_data_ptr)[vstream_key] = now + config.ban_duration;
}
if (has_failed && config.flag_save_failed)
{
auto uuid = boost::uuids::to_string(boost::uuids::random_generator()());
auto path_suffix = absl::Substitute("$0/", config.ext_id);
auto screenshot_extension = ".jpg";
// write failed screenshot to a file
auto path_prefix = absl::StrCat(local_config_.failed_path, path_suffix);
userver::fs::CreateDirectories(fs_task_processor_, path_prefix);
auto path = absl::StrCat(path_prefix, uuid, screenshot_extension);
auto path_draw = absl::StrCat(path_prefix, uuid, "_draw", screenshot_extension);
userver::fs::RewriteFileContents(fs_task_processor_, path, capture_response->body_view());
userver::fs::Chmod(fs_task_processor_, path,
boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write | boost::filesystem::perms::others_read | boost::filesystem::perms::others_write);
// draw failed license plates on the frame
if (!config.work_area.empty())
{
auto wa = convertToAbsolute(config.work_area, frame.cols, frame.rows);
polylines(frame, wa, true, cv::Scalar(0, 200, 0), 2);
}
for (const auto& [bbox, confidence, is_special, license_plates] : detected_vehicles)
{
std::vector<std::vector<cv::Point>> vehicle_polygons;
vehicle_polygons.push_back({{static_cast<int>(bbox[0]), static_cast<int>(bbox[1])},
{static_cast<int>(bbox[2]), static_cast<int>(bbox[1])},
{static_cast<int>(bbox[2]), static_cast<int>(bbox[3])},
{static_cast<int>(bbox[0]), static_cast<int>(bbox[3])}});
polylines(frame, vehicle_polygons, true, is_special ? cv::Scalar(0, 0, 200) : cv::Scalar(200, 0, 0), 2);
}
std::vector<std::vector<cv::Point>> plate_polygons_good;
plate_polygons_good.reserve(detected_plates.size());
std::vector<std::vector<cv::Point>> plate_polygons_failed;
plate_polygons_failed.reserve(detected_plates.size());
for (auto plate_ptr : detected_plates)
{
auto& [bbox, confidence, kpts, plate_class, plate_numbers] = *plate_ptr;
std::vector<cv::Point> p = {{static_cast<int>(kpts[0]), static_cast<int>(kpts[1])},
{static_cast<int>(kpts[2]), static_cast<int>(kpts[3])},
{static_cast<int>(kpts[4]), static_cast<int>(kpts[5])},
{static_cast<int>(kpts[6]), static_cast<int>(kpts[7])}};
if (plate_ptr->plate_numbers.empty())
plate_polygons_failed.push_back(p);
else
plate_polygons_good.push_back(p);
}
if (!plate_polygons_good.empty())
polylines(frame, plate_polygons_good, true, cv::Scalar(2, 105, 255), 2);
if (!plate_polygons_failed.empty())
polylines(frame, plate_polygons_failed, true, cv::Scalar(226, 43, 138), 2);
imwrite(path_draw, frame);
}
}
// for test draw on the frame
/*if (!config.work_area.empty())
{
auto wa = convertToAbsolute(config.work_area, frame.cols, frame.rows);
polylines(frame, wa, true, cv::Scalar(0, 200, 0), 2);
}
for (const auto& vehicle : detected_vehicles)
{
std::vector<std::vector<cv::Point>> vehicle_polygons;
vehicle_polygons.push_back({{static_cast<int>(vehicle.bbox[0]), static_cast<int>(vehicle.bbox[1])},
{static_cast<int>(vehicle.bbox[2]), static_cast<int>(vehicle.bbox[1])},
{static_cast<int>(vehicle.bbox[2]), static_cast<int>(vehicle.bbox[3])},
{static_cast<int>(vehicle.bbox[0]), static_cast<int>(vehicle.bbox[3])}});
polylines(frame, vehicle_polygons, true, vehicle.is_special ? cv::Scalar(0, 0, 200) : cv::Scalar(200, 0, 0), 2);
}
std::vector<std::vector<cv::Point>> plate_polygons;
plate_polygons.reserve(detected_plates.size());
for (auto plate_ptr : detected_plates)
{
auto& plate = *plate_ptr;
plate_polygons.push_back({{static_cast<int>(plate.kpts[0]), static_cast<int>(plate.kpts[1])},
{static_cast<int>(plate.kpts[2]), static_cast<int>(plate.kpts[3])},
{static_cast<int>(plate.kpts[4]), static_cast<int>(plate.kpts[5])},
{static_cast<int>(plate.kpts[6]), static_cast<int>(plate.kpts[7])}});
}
if (!plate_polygons.empty())
polylines(frame, plate_polygons, true, cv::Scalar(2, 102, 255), 2);
imwrite("test.jpg", frame);*/
} catch (std::exception& e)
{
if (config.logs_level <= userver::logging::Level::kError)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kError,
"vstream_key = {}; {}",
vstream_key, e.what());
if (config.delay_after_error.count() > 0)
{
if (config.logs_level <= userver::logging::Level::kError)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kError,
"vstream_key = {}; delay for {}ms",
vstream_key, config.delay_after_error.count());
nextPipeline(std::move(vstream_key), config.delay_after_error);
} else
stopWorkflow(std::move(vstream_key));
return;
}
if (config.logs_level <= userver::logging::Level::kDebug)
USERVER_IMPL_LOG_TO(logger_, userver::logging::Level::kDebug,
"End processPipeline: vstream_key = {};",
vstream_key);
nextPipeline(std::move(vstream_key), config.delay_between_frames);
}
void Workflow::doBanMaintenance()
{
LOG_DEBUG_TO(logger_, "call doBanMaintenance");
auto t_now = std::chrono::steady_clock::now();
auto data_ptr = ban_data.Lock();
absl::erase_if(*data_ptr,
[&t_now](const auto& item)
{
return item.second.tp2 < t_now;
});
}
void Workflow::doEventsLogMaintenance() const
{
LOG_DEBUG_TO(logger_, "call doEventsLogMaintenance");
auto tp = std::chrono::system_clock::now() - local_config_.events_log_ttl;
LOG_DEBUG_TO(logger_) << "delete event logs older than " << tp;
const userver::storages::postgres::Query query{SQL_REMOVE_OLD_EVENTS};
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
trx.Execute(query, userver::storages::postgres::TimePointTz{tp});
trx.Commit();
} catch (std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(logger_) << e.what();
return;
}
// delete old screenshot files
const HashSet<std::string> img_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".ppm", ".tiff"};
if (std::filesystem::exists(local_config_.events_screenshots_path))
for (const auto& dir_entry : std::filesystem::recursive_directory_iterator(local_config_.events_screenshots_path))
if (dir_entry.is_regular_file() && img_extensions.contains(dir_entry.path().extension().string()))
{
if (auto t_file = std::chrono::file_clock::to_sys(dir_entry.last_write_time()); t_file < tp)
std::filesystem::remove(dir_entry);
}
// delete old failed license plates screenshot files
tp = std::chrono::system_clock::now() - local_config_.failed_ttl;
if (std::filesystem::exists(local_config_.failed_path))
for (const auto& dir_entry : std::filesystem::recursive_directory_iterator(local_config_.failed_path))
if (dir_entry.is_regular_file() && img_extensions.contains(dir_entry.path().extension().string()))
{
if (auto t_file = std::chrono::file_clock::to_sys(dir_entry.last_write_time()); t_file < tp)
std::filesystem::remove(dir_entry);
}
}
void Workflow::nextPipeline(std::string&& vstream_key, const std::chrono::milliseconds delay)
{
userver::engine::InterruptibleSleepFor(delay);
bool do_next = false;
bool is_timeout = false;
// scope for accessing concurrent variable
{
const auto now = std::chrono::steady_clock::now();
auto data_ptr = vstream_timeouts.Lock();
if (data_ptr->contains(vstream_key))
if (data_ptr->at(vstream_key) < now)
{
data_ptr->erase(vstream_key);
is_timeout = true;
}
}
// scope for accessing concurrent variable
{
auto data_ptr = being_processed_vstreams.Lock();
if (data_ptr->contains(vstream_key))
{
if (data_ptr->at(vstream_key) && !is_timeout)
do_next = true;
else
data_ptr->erase(vstream_key);
}
}
if (is_timeout)
LOG_INFO_TO(logger_,
"Stopping a workflow by timeout: vstream_key = {};",
vstream_key);
if (do_next)
tasks_.Detach(AsyncNoSpan(task_processor_, &Workflow::processPipeline, this, std::move(vstream_key)));
}
// Inference pipeline methods
std::vector<float> Workflow::preprocessImageForVdNet(const cv::Mat& img, const int32_t width, const int32_t height, cv::Point2f& shift,
double& scale)
{
return preprocessImageForLpdNet(img, width, height, shift, scale);
}
std::vector<float> Workflow::preprocessImageForVcNet(const cv::Mat& img, const int32_t width, const int32_t height)
{
cv::Mat out(height, width, CV_8UC3);
resize(img, out, out.size(), 0, 0, cv::INTER_AREA);
constexpr int32_t channels = 3;
const int32_t input_size = channels * width * height;
std::vector<float> input_buffer(input_size);
/*const std::vector<float> means = {0.485, 0.456, 0.406};
const std::vector<float> std_d = {0.229, 0.224, 0.225};*/
const std::vector<float> means = {0.5, 0.5, 0.5};
const std::vector<float> std_d = {0.5, 0.5, 0.5};
for (auto c = 0; c < channels; ++c)
for (auto h = 0; h < height; ++h)
for (auto w = 0; w < width; ++w)
input_buffer[c * height * width + h * width + w] =
(static_cast<float>(out.at<cv::Vec3b>(h, w)[2 - c]) / 255.0f - means[c]) / std_d[c];
return input_buffer;
}
std::vector<float> Workflow::preprocessImageForLpdNet(const cv::Mat& img, const int32_t width, const int32_t height, cv::Point2f& shift,
double& scale)
{
const auto r_w = width / (img.cols * 1.0);
const auto r_h = height / (img.rows * 1.0);
scale = fmin(r_w, r_h);
const auto ww = static_cast<int>(lround(scale * img.cols));
const auto hh = static_cast<int>(lround(scale * img.rows));
shift.x = static_cast<float>(width - ww) / 2;
shift.y = static_cast<float>(height - hh) / 2;
cv::Mat re(hh, ww, CV_8UC3);
resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR);
const int border_top = static_cast<int>(shift.y);
const int border_bottom = height - hh - border_top;
const int border_left = static_cast<int>(shift.x);
const int border_right = width - ww - border_left;
cv::Mat out;
copyMakeBorder(re, out, border_top, border_bottom,
border_left, border_right, cv::BORDER_CONSTANT, {114, 114, 114});
/*cv::Mat out(height, width, CV_8UC3, cv::Scalar(0, 0, 0));
re.copyTo(out(cv::Rect(shift.x, shift.y, re.cols, re.rows)));*/
// for test
// cv::imwrite(absl::Substitute("p_$0_$1.jpg", border_left, border_top), out);
constexpr int32_t channels = 3;
const int32_t input_size = channels * width * height;
std::vector<float> input_buffer(input_size);
for (auto c = 0; c < channels; ++c)
for (auto h = 0; h < height; ++h)
for (auto w = 0; w < width; ++w)
input_buffer[c * height * width + h * width + w] =
static_cast<float>(out.at<cv::Vec3b>(h, w)[2 - c]) / 255.0f;
return input_buffer;
}
std::vector<float> Workflow::preprocessImageForLprNet(const cv::Mat& img, const int32_t width, const int32_t height, cv::Point2f& shift, double& scale)
{
const auto r_w = width / (img.cols * 1.0);
const auto r_h = height / (img.rows * 1.0);
scale = fmin(r_w, r_h);
const auto ww = static_cast<int>(lround(scale * img.cols));
const auto hh = static_cast<int>(lround(scale * img.rows));
shift.x = static_cast<float>(width - ww) / 2;
shift.y = static_cast<float>(height - hh) / 2;
cv::Mat re(hh, ww, CV_8UC3);
resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR);
cv::Mat out;
copyMakeBorder(re, out, static_cast<int>(shift.y), static_cast<int>(shift.y),
static_cast<int>(shift.x), static_cast<int>(shift.x), cv::BORDER_CONSTANT, {114, 114, 114});
/*cv::Mat out(height, width, CV_8UC3, cv::Scalar(0, 0, 0));
re.copyTo(out(cv::Rect(shift.x, shift.y, re.cols, re.rows)));*/
// for test
// cv::imwrite("plate.jpg", out);