Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/docker/platerec_installer/installer_helpers.py
1091 views
1
import os
2
import platform
3
import subprocess
4
import sys
5
import webbrowser
6
from pathlib import Path
7
from ssl import SSLError
8
9
from stream_config import DEFAULT_CONFIG, base_config
10
11
try:
12
from urllib.error import URLError
13
from urllib.request import Request, urlopen
14
except ImportError:
15
from urllib2 import Request, URLError, urlopen # type: ignore
16
17
18
def get_os():
19
os_system = platform.system()
20
if os_system == "Windows":
21
return "Windows"
22
elif os_system == "Linux":
23
return "Linux"
24
elif os_system == "Darwin":
25
return "Mac OS"
26
return os_system
27
28
29
class DockerPermissionError(Exception):
30
pass
31
32
33
def verify_docker_install():
34
try:
35
subprocess.check_output(
36
"docker info".split(), stderr=subprocess.STDOUT
37
).decode()
38
return True
39
except subprocess.CalledProcessError as exc:
40
output = exc.output.decode()
41
perm_error = "Got permission denied while trying to connect"
42
if perm_error in output:
43
raise DockerPermissionError(output) from exc
44
return False
45
46
47
def get_container_id(image):
48
cmd = f"docker ps -q --filter ancestor={image}"
49
output = subprocess.check_output(cmd.split())
50
return output.decode()
51
52
53
def stop_container(image):
54
container_id = get_container_id(image)
55
if container_id:
56
cmd = f"docker stop {container_id}"
57
os.system(cmd)
58
return container_id
59
60
61
def get_home(product="stream"):
62
return str(Path.home() / product)
63
64
65
def get_image(image):
66
images = (
67
subprocess.check_output(
68
["docker", "images", "--format", '"{{.Repository}}:{{.Tag}}"', image]
69
)
70
.decode()
71
.split("\n")
72
)
73
return images[0].replace('"', "")
74
75
76
def pull_docker(image):
77
if get_container_id(image):
78
stop_container(image)
79
pull_cmd = f"docker pull {image}"
80
os.system(pull_cmd)
81
82
83
def read_config(home):
84
try:
85
config = Path(home) / "config.ini"
86
conf = ""
87
f = open(config)
88
for line in f:
89
conf += line
90
f.close()
91
return conf
92
except OSError: # file not found
93
return DEFAULT_CONFIG
94
95
96
def write_config(home, config):
97
try:
98
path = Path(home) / "config.ini"
99
os.makedirs(os.path.dirname(path), exist_ok=True)
100
result, error = base_config(path, config)
101
if error:
102
return False, error
103
with open(path, "w+") as conf:
104
for line in config:
105
conf.write(line)
106
return True, ""
107
except Exception:
108
return (
109
False,
110
f"The Installation Directory is not valid. Please enter a valid folder, such as {get_home()}",
111
)
112
113
114
def verify_token(token, license_key, get_license=True, product="stream"):
115
path = "stream/license" if product == "stream" else "sdk-webhooks"
116
if not (token and license_key):
117
return False, "API token and license key is required."
118
try:
119
req = Request(
120
f"https://api.platerecognizer.com/v1/{path}/{license_key.strip()}/"
121
)
122
req.add_header("Authorization", f"Token {token.strip()}")
123
urlopen(req).read()
124
return True, None
125
except SSLError:
126
req = Request(
127
f"http://api.platerecognizer.com/v1/{path}/{license_key.strip()}/"
128
)
129
req.add_header("Authorization", f"Token {token.strip()}")
130
urlopen(req).read()
131
return True, None
132
except URLError as e:
133
if "404" in str(e) and get_license:
134
return (
135
False,
136
"The License Key cannot be found. Please use the correct License Key.",
137
)
138
elif str(403) in str(e):
139
return False, "The API Token cannot be found. Please use the correct Token."
140
else:
141
return True, None
142
143
144
def is_valid_port(port):
145
try:
146
return 0 <= int(port) <= 65535
147
except ValueError:
148
return False
149
150
151
def resource_path(relative_path):
152
# get absolute path to resource
153
try:
154
# PyInstaller creates a temp folder and stores path in _MEIPASS
155
base_path = sys._MEIPASS
156
except Exception:
157
base_path = os.path.abspath(".")
158
159
return os.path.join(base_path, relative_path)
160
161
162
def uninstall_docker_image(hardware):
163
container_id = get_container_id(hardware)
164
if container_id:
165
cmd = f"docker container rm {container_id}"
166
os.system(cmd)
167
cmd = f'docker rmi "{hardware}" -f'
168
os.system(cmd)
169
cmd = "docker image prune -f"
170
os.system(cmd)
171
return [None, "Image successfully uninstalled."]
172
173
174
def launch_browser(url):
175
os_platform = get_os()
176
if os_platform in ["Windows", "Darwin"]:
177
return webbrowser.open(url)
178
elif os_platform == "Linux":
179
opener = "xdg-open"
180
# remove all environment variables that contain the 'tmp' directory.
181
my_env = dict(os.environ)
182
to_delete = []
183
for k, v in my_env.items():
184
if k != "PATH" and "tmp" in v:
185
to_delete.append(k)
186
for k in to_delete:
187
my_env.pop(k, None)
188
try:
189
subprocess.call([opener, url], env=my_env, shell=False)
190
except (
191
FileNotFoundError
192
): # [Errno 2] No such file or directory: 'xdg-open': 'xdg-open'
193
print(f"Unable to launch browser: {opener} command not found")
194
else:
195
raise Exception(f"Unrecognized OS platform: {os_platform}")
196
197