1-
2- import torch
3- import time
4- import json
5- import io
61import _thread as thread
7- from multiprocessing import Process
8- from PIL import Image ,UnidentifiedImageError
9- import torch .nn .functional as F
102import ast
3+ import io
4+ import json
5+ import os
116import sqlite3
12- import numpy as np
13- import warnings
147import sys
15- import os
8+ import time
9+ import warnings
10+ from multiprocessing import Process
11+
12+ import numpy as np
13+ import torch
14+ import torch .nn .functional as F
15+ from PIL import Image , UnidentifiedImageError
16+
1617sys .path .insert (0 , os .path .join (os .path .dirname (os .path .realpath (__file__ )), "../../" ))
1718
18- from process import YOLODetector
19- from shared import SharedOptions
19+ import argparse
20+ import traceback
2021
2122import torchvision .transforms as transforms
22- import traceback
2323from PIL import UnidentifiedImageError
24- import argparse
24+ from process import YOLODetector
25+ from shared import SharedOptions
2526
2627parser = argparse .ArgumentParser ()
27- parser .add_argument ("--model" ,type = str ,default = None )
28- parser .add_argument ("--name" ,type = str ,default = None )
28+ parser .add_argument ("--model" , type = str , default = None )
29+ parser .add_argument ("--name" , type = str , default = None )
2930
3031opt = parser .parse_args ()
3132
33+
3234def objectdetection (thread_name : str , delay : float ):
3335
3436 MODE = SharedOptions .MODE
@@ -40,49 +42,50 @@ def objectdetection(thread_name: str, delay: float):
4042 if opt .name == None :
4143 IMAGE_QUEUE = "detection_queue"
4244 else :
43- IMAGE_QUEUE = opt .name + "_queue"
44-
45+ IMAGE_QUEUE = opt .name + "_queue"
46+
4547 if opt .model == None :
46- model_path = os .path .join (SHARED_APP_DIR ,SharedOptions .SETTINGS .DETECTION_MODEL )
48+ model_path = os .path .join (
49+ SHARED_APP_DIR , SharedOptions .SETTINGS .DETECTION_MODEL
50+ )
4751 else :
4852 model_path = opt .model
49-
53+
5054 if MODE == "High" :
5155
5256 reso = SharedOptions .SETTINGS .DETECTION_HIGH
53-
57+
5458 elif MODE == "Medium" :
55-
59+
5660 reso = SharedOptions .SETTINGS .DETECTION_MEDIUM
57-
61+
5862 elif MODE == "Low" :
5963
6064 reso = SharedOptions .SETTINGS .DETECTION_LOW
6165
62- detector = YOLODetector (model_path ,reso ,cuda = CUDA_MODE )
66+ detector = YOLODetector (model_path , reso , cuda = CUDA_MODE )
6367 while True :
64- queue = db .lrange (IMAGE_QUEUE ,0 ,0 )
68+ queue = db .lrange (IMAGE_QUEUE , 0 , 0 )
69+
70+ db .ltrim (IMAGE_QUEUE , len (queue ), - 1 )
6571
66- db .ltrim (IMAGE_QUEUE ,len (queue ), - 1 )
67-
6872 if len (queue ) > 0 :
6973
7074 for req_data in queue :
71-
72- req_data = json .JSONDecoder ().decode (req_data )
7375
76+ req_data = json .JSONDecoder ().decode (req_data )
7477
7578 img_id = req_data ["imgid" ]
7679 req_id = req_data ["reqid" ]
7780 req_type = req_data ["reqtype" ]
7881 threshold = float (req_data ["minconfidence" ])
79-
82+
8083 try :
8184
82- img = os .path .join (TEMP_PATH ,img_id )
83-
84- det = detector .predict (img ,threshold )
85-
85+ img = os .path .join (TEMP_PATH , img_id )
86+
87+ det = detector .predict (img , threshold )
88+
8689 outputs = []
8790
8891 for * xyxy , conf , cls in reversed (det ):
@@ -94,32 +97,47 @@ def objectdetection(thread_name: str, delay: float):
9497
9598 label = detector .names [int (cls .item ())]
9699
97- detection = {"confidence" :score ,"label" :label , "x_min" :int (x_min ), "y_min" :int (y_min ),"x_max" :int (x_max ), "y_max" :int (y_max )}
100+ detection = {
101+ "confidence" : score ,
102+ "label" : label ,
103+ "x_min" : int (x_min ),
104+ "y_min" : int (y_min ),
105+ "x_max" : int (x_max ),
106+ "y_max" : int (y_max ),
107+ }
98108
99109 outputs .append (detection )
100110
101- output = {"success" :True ,"predictions" :outputs }
111+ output = {"success" : True , "predictions" : outputs }
102112
103113 except UnidentifiedImageError :
104114 err_trace = traceback .format_exc ()
105- print (err_trace ,file = sys .stderr ,flush = True )
115+ print (err_trace , file = sys .stderr , flush = True )
116+
117+ output = {
118+ "success" : False ,
119+ "error" : "invalid image file" ,
120+ "code" : 400 ,
121+ }
106122
107- output = {"success" :False , "error" :"invalid image file" ,"code" :400 }
108-
109123 except Exception :
110124
111125 err_trace = traceback .format_exc ()
112- print (err_trace ,file = sys .stderr ,flush = True )
113-
114- output = {"success" :False , "error" :"error occured on the server" ,"code" :500 }
115-
126+ print (err_trace , file = sys .stderr , flush = True )
127+
128+ output = {
129+ "success" : False ,
130+ "error" : "error occured on the server" ,
131+ "code" : 500 ,
132+ }
133+
116134 finally :
117- db .set (req_id ,json .dumps (output ))
135+ db .set (req_id , json .dumps (output ))
118136 if os .path .exists (TEMP_PATH + img_id ):
119137 os .remove (img )
120138
121139 time .sleep (delay )
122140
123- p = Process (target = objectdetection ,args = ("" ,SharedOptions .SLEEP_TIME ))
124- p .start ()
125141
142+ p = Process (target = objectdetection , args = ("" , SharedOptions .SLEEP_TIME ))
143+ p .start ()
0 commit comments