Path: blob/master/docker/sdk_manager/PlateRec_SDK_Manager.py
1085 views
#!/usr/bin/env python12import os3import subprocess4import sys5import time6import webbrowser78try:9from urllib.error import URLError10from urllib.request import Request, urlopen11except ImportError:12from urllib2 import ( # type: ignore13Request,14URLError, # type: ignore15urlopen,16)171819def verify_docker_install():20try:21subprocess.check_output("docker info --format '{{.ServerVersion}}'".split())22return True23except OSError:24return False252627def test_install(port, token, counter=0):28try:29url = f"http://localhost:{port}/v1/plate-reader/"30req = Request(url)31req.get_method = lambda: "POST"32req.add_header("Authorization", f"Token {token}")33urlopen(req).read()34return True35except Exception:36if counter < 20:37time.sleep(2)38counter += 139return test_install(port, token, counter=counter)40else:41return False424344def get_container_id(image):45cmd = f"docker ps -q --filter ancestor={image}"46output = subprocess.check_output(cmd.split())47return output.decode()484950def install_pr(51image,52auto_start_container,53port,54token,55license_key,56extra_args="",57docker_version="docker",58image_version="latest",59):60if get_container_id(image):61stop_container(image)62pull_cmd = f"docker pull {image}:{image_version}"63os.system(pull_cmd)64run_cmd = "{} run {} -t {} -p {}:8080 -v license:/license -e TOKEN={} -e LICENSE_KEY={} {}".format(65docker_version,66"--restart unless-stopped" if auto_start_container else "--rm",67extra_args,68port,69token,70license_key,71image,72)73if os.name == "nt":74os.system(f'start /b "" {run_cmd}')75else:76os.system(run_cmd + "&")77if test_install(port, token):78print("Installation successful")79else:80print("Installation was not successful")8182print("\nUse the command below to run the sdk again.")83print(run_cmd)84print(85'\nTo use the SDK endpoint call: curl -F "upload=@my_file.jpg" http://localhost:8080/v1/plate-reader/'86)87print("To exit this program, just close this Command Line Interface window.\n")888990def get_image():91images = (92subprocess.check_output(93"docker images --format '{{.Repository}}' platerecognizer/alpr*".split()94)95.decode()96.split("\n")97)98return images[0].replace("'", "")99100101def verify_token(token, license_key, get_license=True):102try:103req = Request(f"https://api.platerecognizer.com/v1/sdk-webhooks/{license_key}/")104req.add_header("Authorization", f"Token {token}")105urlopen(req).read()106return True107except URLError as e:108if "404" in str(e) and get_license:109print("License Key is incorrect!!")110return False111elif str(403) in str(e):112print("Api Token is incorrect!!")113return False114else:115return True116117return False118119120def get_token_input(get_license=True, open_page=True):121print(122"\nSee your account credentials on https://app.platerecognizer.com/accounts/plan/. We opened up the account page on your browser."123)124if open_page:125webbrowser.open("https://app.platerecognizer.com/accounts/plan/#sdk")126time.sleep(1)127token = str(input("\nEnter the API Token for the SDK > ")).strip()128if get_license:129license_key = str(input("Enter the License Key for the SDK > ")).strip()130else:131license_key = True132if (133not token134or not license_key135or not verify_token(token, license_key, get_license=get_license)136):137print(138"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."139)140return get_token_input(get_license=get_license, open_page=False)141else:142return token, license_key143144145def stop_container(image):146container_id = get_container_id(image)147if container_id:148cmd = f"docker stop {container_id}"149os.system(cmd)150return container_id151152153def install():154hardwares = (155"x86 / Intel CPU",156"Raspberry",157"GPU (Nvidia Only)",158"Jetson Nano",159"Quit",160)161hardware = "1"162print("\n")163for ind, choice in enumerate(hardwares):164print(f"{ind + 1}) {choice}")165while True:166choice = str(input("What is the hardware of this machine > ") or "")167168if choice == "5":169print("Quit!\n")170return main()171if choice in ["1", "2", "3", "4"]:172hardware = choice173break174else:175print("Incorrect Choice")176177token, license_key = get_token_input(get_license=True)178179auto_start_container = False180port = "8080"181print("\nWould you like to start the container on boot?")182print("1) yes")183print("2) no")184185image = None186187while True:188choice = str(input("Pick an action > ") or "")189if choice in ["1", "2"]:190if choice == "1":191auto_start_container = True192break193print("Incorrect choice")194195while True:196try:197port = int(input("\nSet the container port [default=8080] > ") or 8080)198if 0 <= port <= 65535:199break200else:201print("Incorrect Value, Enter a value between 0 and 65535")202203except ValueError:204print("Incorrect Value, Enter a value between 0 and 65535")205206print("\nStarting Installation")207208if hardware == "1":209image = "platerecognizer/alpr"210install_pr(image, auto_start_container, port, token, license_key)211212elif hardware == "2":213image = "platerecognizer/alpr-raspberry-pi"214install_pr(image, auto_start_container, port, token, license_key)215216elif hardware == "3":217image = "platerecognizer/alpr-gpu"218install_pr(219image,220auto_start_container,221port,222token,223license_key,224extra_args="--runtime nvidia",225)226227elif hardware == "4":228image = "platerecognizer/alpr-jetson"229install_pr(230image,231auto_start_container,232port,233token,234license_key,235extra_args="--runtime nvidia",236docker_version="nvidia-docker",237)238239return main()240241242def update():243version = str(244input(245"Which version would you like to install? [press Enter for latest version] "246)247or "latest"248)249token, license_key = get_token_input(get_license=True)250image = get_image()251if not image:252print(253"PlateRecognizer SDK is not installed, Please select Install. Quitting!!\n"254)255return main()256stop_container(image)257extra_args = ""258docker_version = "docker"259if "jetson" in image:260extra_args = "--runtime nvidia"261docker_version = "nvidia-docker"262elif "gpu" in image:263extra_args = "--runtime nvidia"264265auto_start_container = False266install_pr(267image,268auto_start_container,2698080,270token,271license_key,272extra_args=extra_args,273docker_version=docker_version,274image_version=version,275)276277return main()278279280def uninstall():281image = get_image()282if "platerecognizer" not in image:283print(284"PlateRecognizer SDK is not installed, Please select Install. (press Ctrl-C to exit).\n"285)286return main()287288print("\n1) Uninstall the SDK. You can then install it on another machine.")289print(290"2) Uninstall the SDK and remove the container. You can then install the SDK on another machine."291)292print("3) Quit")293while True:294uninstall_choice = str(input("Pick an action > ") or "")295if uninstall_choice in ["1", "2", "3"]:296if uninstall_choice == "3":297print("Quitting!!\n")298return main()299break300else:301print("Incorrect choice")302303token, _ = get_token_input(get_license=False)304if uninstall_choice == "1":305stop_container(image)306cmd = f"docker run --rm -t -v license:/license -e TOKEN={token} -e UNINSTALL=1 {image}"307308os.system(cmd)309return main()310311elif uninstall_choice == "2":312container_id = stop_container(image)313cmd = f"docker run --rm -t -v license:/license -e TOKEN={token} -e UNINSTALL=1 {image}"314os.system(cmd)315container_id = get_container_id(image)316if container_id:317cmd = f"docker container rm {container_id}"318os.system(cmd)319cmd = f'docker rmi "{image}"'320os.system(cmd)321print("Container removed successfully!!\n")322return main()323324325def main():326print("Plate Recognizer SDK Manager.")327print(328"If you face any problems, please let us know at https://platerecognizer.com/contact and include a screenshot of the error message.\n"329)330331if not verify_docker_install():332print(333"Docker is not installed, Follow 'https://docs.docker.com/install/' to install docker for your machine."334)335print("Program will exit in 30seconds (press Ctrl-C to exit now).")336webbrowser.open("https://docs.docker.com/install/")337time.sleep(30)338sys.exit(1)339340actions = ("Install", "Update", "Uninstall", "Quit")341action_choice = 1342343for ind, choice in enumerate(actions):344print(f"{ind + 1}) {choice}")345while True:346choice = str(input("Pick an action > ") or "")347if choice == "4":348print("Quit!")349sys.exit(1)350if choice in ["1", "2", "3"]:351action_choice = choice352break353else:354print("Incorrect Choice")355356if action_choice == "1":357return install()358359elif action_choice == "2":360return update()361362elif action_choice == "3":363return uninstall()364365366if __name__ == "__main__":367main()368369370