Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/docker/sdk_manager/PlateRec_SDK_Manager.py
1085 views
1
#!/usr/bin/env python
2
3
import os
4
import subprocess
5
import sys
6
import time
7
import webbrowser
8
9
try:
10
from urllib.error import URLError
11
from urllib.request import Request, urlopen
12
except ImportError:
13
from urllib2 import ( # type: ignore
14
Request,
15
URLError, # type: ignore
16
urlopen,
17
)
18
19
20
def verify_docker_install():
21
try:
22
subprocess.check_output("docker info --format '{{.ServerVersion}}'".split())
23
return True
24
except OSError:
25
return False
26
27
28
def test_install(port, token, counter=0):
29
try:
30
url = f"http://localhost:{port}/v1/plate-reader/"
31
req = Request(url)
32
req.get_method = lambda: "POST"
33
req.add_header("Authorization", f"Token {token}")
34
urlopen(req).read()
35
return True
36
except Exception:
37
if counter < 20:
38
time.sleep(2)
39
counter += 1
40
return test_install(port, token, counter=counter)
41
else:
42
return False
43
44
45
def get_container_id(image):
46
cmd = f"docker ps -q --filter ancestor={image}"
47
output = subprocess.check_output(cmd.split())
48
return output.decode()
49
50
51
def install_pr(
52
image,
53
auto_start_container,
54
port,
55
token,
56
license_key,
57
extra_args="",
58
docker_version="docker",
59
image_version="latest",
60
):
61
if get_container_id(image):
62
stop_container(image)
63
pull_cmd = f"docker pull {image}:{image_version}"
64
os.system(pull_cmd)
65
run_cmd = "{} run {} -t {} -p {}:8080 -v license:/license -e TOKEN={} -e LICENSE_KEY={} {}".format(
66
docker_version,
67
"--restart unless-stopped" if auto_start_container else "--rm",
68
extra_args,
69
port,
70
token,
71
license_key,
72
image,
73
)
74
if os.name == "nt":
75
os.system(f'start /b "" {run_cmd}')
76
else:
77
os.system(run_cmd + "&")
78
if test_install(port, token):
79
print("Installation successful")
80
else:
81
print("Installation was not successful")
82
83
print("\nUse the command below to run the sdk again.")
84
print(run_cmd)
85
print(
86
'\nTo use the SDK endpoint call: curl -F "upload=@my_file.jpg" http://localhost:8080/v1/plate-reader/'
87
)
88
print("To exit this program, just close this Command Line Interface window.\n")
89
90
91
def get_image():
92
images = (
93
subprocess.check_output(
94
"docker images --format '{{.Repository}}' platerecognizer/alpr*".split()
95
)
96
.decode()
97
.split("\n")
98
)
99
return images[0].replace("'", "")
100
101
102
def verify_token(token, license_key, get_license=True):
103
try:
104
req = Request(f"https://api.platerecognizer.com/v1/sdk-webhooks/{license_key}/")
105
req.add_header("Authorization", f"Token {token}")
106
urlopen(req).read()
107
return True
108
except URLError as e:
109
if "404" in str(e) and get_license:
110
print("License Key is incorrect!!")
111
return False
112
elif str(403) in str(e):
113
print("Api Token is incorrect!!")
114
return False
115
else:
116
return True
117
118
return False
119
120
121
def get_token_input(get_license=True, open_page=True):
122
print(
123
"\nSee your account credentials on https://app.platerecognizer.com/accounts/plan/. We opened up the account page on your browser."
124
)
125
if open_page:
126
webbrowser.open("https://app.platerecognizer.com/accounts/plan/#sdk")
127
time.sleep(1)
128
token = str(input("\nEnter the API Token for the SDK > ")).strip()
129
if get_license:
130
license_key = str(input("Enter the License Key for the SDK > ")).strip()
131
else:
132
license_key = True
133
if (
134
not token
135
or not license_key
136
or not verify_token(token, license_key, get_license=get_license)
137
):
138
print(
139
"We do not recognize this API Token or License Key in our system. Please refer to your account page and try again. Press Control-C to exit."
140
)
141
return get_token_input(get_license=get_license, open_page=False)
142
else:
143
return token, license_key
144
145
146
def stop_container(image):
147
container_id = get_container_id(image)
148
if container_id:
149
cmd = f"docker stop {container_id}"
150
os.system(cmd)
151
return container_id
152
153
154
def install():
155
hardwares = (
156
"x86 / Intel CPU",
157
"Raspberry",
158
"GPU (Nvidia Only)",
159
"Jetson Nano",
160
"Quit",
161
)
162
hardware = "1"
163
print("\n")
164
for ind, choice in enumerate(hardwares):
165
print(f"{ind + 1}) {choice}")
166
while True:
167
choice = str(input("What is the hardware of this machine > ") or "")
168
169
if choice == "5":
170
print("Quit!\n")
171
return main()
172
if choice in ["1", "2", "3", "4"]:
173
hardware = choice
174
break
175
else:
176
print("Incorrect Choice")
177
178
token, license_key = get_token_input(get_license=True)
179
180
auto_start_container = False
181
port = "8080"
182
print("\nWould you like to start the container on boot?")
183
print("1) yes")
184
print("2) no")
185
186
image = None
187
188
while True:
189
choice = str(input("Pick an action > ") or "")
190
if choice in ["1", "2"]:
191
if choice == "1":
192
auto_start_container = True
193
break
194
print("Incorrect choice")
195
196
while True:
197
try:
198
port = int(input("\nSet the container port [default=8080] > ") or 8080)
199
if 0 <= port <= 65535:
200
break
201
else:
202
print("Incorrect Value, Enter a value between 0 and 65535")
203
204
except ValueError:
205
print("Incorrect Value, Enter a value between 0 and 65535")
206
207
print("\nStarting Installation")
208
209
if hardware == "1":
210
image = "platerecognizer/alpr"
211
install_pr(image, auto_start_container, port, token, license_key)
212
213
elif hardware == "2":
214
image = "platerecognizer/alpr-raspberry-pi"
215
install_pr(image, auto_start_container, port, token, license_key)
216
217
elif hardware == "3":
218
image = "platerecognizer/alpr-gpu"
219
install_pr(
220
image,
221
auto_start_container,
222
port,
223
token,
224
license_key,
225
extra_args="--runtime nvidia",
226
)
227
228
elif hardware == "4":
229
image = "platerecognizer/alpr-jetson"
230
install_pr(
231
image,
232
auto_start_container,
233
port,
234
token,
235
license_key,
236
extra_args="--runtime nvidia",
237
docker_version="nvidia-docker",
238
)
239
240
return main()
241
242
243
def update():
244
version = str(
245
input(
246
"Which version would you like to install? [press Enter for latest version] "
247
)
248
or "latest"
249
)
250
token, license_key = get_token_input(get_license=True)
251
image = get_image()
252
if not image:
253
print(
254
"PlateRecognizer SDK is not installed, Please select Install. Quitting!!\n"
255
)
256
return main()
257
stop_container(image)
258
extra_args = ""
259
docker_version = "docker"
260
if "jetson" in image:
261
extra_args = "--runtime nvidia"
262
docker_version = "nvidia-docker"
263
elif "gpu" in image:
264
extra_args = "--runtime nvidia"
265
266
auto_start_container = False
267
install_pr(
268
image,
269
auto_start_container,
270
8080,
271
token,
272
license_key,
273
extra_args=extra_args,
274
docker_version=docker_version,
275
image_version=version,
276
)
277
278
return main()
279
280
281
def uninstall():
282
image = get_image()
283
if "platerecognizer" not in image:
284
print(
285
"PlateRecognizer SDK is not installed, Please select Install. (press Ctrl-C to exit).\n"
286
)
287
return main()
288
289
print("\n1) Uninstall the SDK. You can then install it on another machine.")
290
print(
291
"2) Uninstall the SDK and remove the container. You can then install the SDK on another machine."
292
)
293
print("3) Quit")
294
while True:
295
uninstall_choice = str(input("Pick an action > ") or "")
296
if uninstall_choice in ["1", "2", "3"]:
297
if uninstall_choice == "3":
298
print("Quitting!!\n")
299
return main()
300
break
301
else:
302
print("Incorrect choice")
303
304
token, _ = get_token_input(get_license=False)
305
if uninstall_choice == "1":
306
stop_container(image)
307
cmd = f"docker run --rm -t -v license:/license -e TOKEN={token} -e UNINSTALL=1 {image}"
308
309
os.system(cmd)
310
return main()
311
312
elif uninstall_choice == "2":
313
container_id = stop_container(image)
314
cmd = f"docker run --rm -t -v license:/license -e TOKEN={token} -e UNINSTALL=1 {image}"
315
os.system(cmd)
316
container_id = get_container_id(image)
317
if container_id:
318
cmd = f"docker container rm {container_id}"
319
os.system(cmd)
320
cmd = f'docker rmi "{image}"'
321
os.system(cmd)
322
print("Container removed successfully!!\n")
323
return main()
324
325
326
def main():
327
print("Plate Recognizer SDK Manager.")
328
print(
329
"If you face any problems, please let us know at https://platerecognizer.com/contact and include a screenshot of the error message.\n"
330
)
331
332
if not verify_docker_install():
333
print(
334
"Docker is not installed, Follow 'https://docs.docker.com/install/' to install docker for your machine."
335
)
336
print("Program will exit in 30seconds (press Ctrl-C to exit now).")
337
webbrowser.open("https://docs.docker.com/install/")
338
time.sleep(30)
339
sys.exit(1)
340
341
actions = ("Install", "Update", "Uninstall", "Quit")
342
action_choice = 1
343
344
for ind, choice in enumerate(actions):
345
print(f"{ind + 1}) {choice}")
346
while True:
347
choice = str(input("Pick an action > ") or "")
348
if choice == "4":
349
print("Quit!")
350
sys.exit(1)
351
if choice in ["1", "2", "3"]:
352
action_choice = choice
353
break
354
else:
355
print("Incorrect Choice")
356
357
if action_choice == "1":
358
return install()
359
360
elif action_choice == "2":
361
return update()
362
363
elif action_choice == "3":
364
return uninstall()
365
366
367
if __name__ == "__main__":
368
main()
369
370