def download_file(source_url, filename=None, folder=None): # Validity Checks if filename is None: filename = os.path.basename(source_url) if len(filename) < 1: logging.error(f"URL does not contain filename. No filename given") return ( False, f"URL does not contain filename. No filename given. Please provide a filename", None, ) if folder is None: filepath = filename else: if not os.path.exists(folder): os.makedirs(folder) filepath = os.path.join(folder, filename) try: # Download the file req = requests.get(source_url, allow_redirects=True) except Exception as e: logging.error(f"Failed to get the file due to error: {e}") return False, f"Failed to get the file due to error: {e}", None # Write the file to disk with open(filepath, "wb") as f: f.write(req.content) return True, f"File Downloaded in location {filepath}", filepath
def __init__(self, username: str, password: str, watch_folder: str, destination_folder: str, host: str, debug: bool = False, scanning_interval: int = 1, template: str = "{artist}/{album}/{title}.mp3"): super().__init__(watch_folder=watch_folder, target_folder=destination_folder, debug=debug, recursive=True, thread_name="Main thread of owncloud watcher", scanning_interval=scanning_interval, template=template) self._username = username self._host = host self._oc = owncloud.Client(host) _wait = 5 while True: try: self._oc.login(user_id=username, password=password) break except owncloud.owncloud.HTTPResponseError as e: logging.error( f"Got Connection Error while connection to owncloud. Waiting {_wait}min for retry. " f"HTTP-Error: {e.status_code}") time.sleep(_wait * 60) logging.info( f"Connected to owncloud {host}. Host runs version {self._oc.get_version()}" )
def load_config(config_path): config = {} try: with open("config.json") as f: config = json.load(f) logging.info( f"Config Loaded. JSON Contents: \n{json.dumps(config, indent=4)}") except Exception as e: logging.error( f"Failed to Load Config, using default config Params. Error: {e}") return config
def download_weights(self): folder = self.config.get("weights_folder", "weights") # Hardcoded URLs bin_url = "https://download.01.org/opencv/2020/openvinotoolkit/2020.3/open_model_zoo/models_bin/1/face-detection-0104/FP16/face-detection-0104.bin" xml_url = "https://download.01.org/opencv/2020/openvinotoolkit/2020.3/open_model_zoo/models_bin/1/face-detection-0104/FP16/face-detection-0104.xml" # Get Filenames bin_filename = os.path.basename(bin_url) xml_filename = os.path.basename(xml_url) # Generate Path bin_path = os.path.join(folder, bin_filename) xml_path = os.path.join(folder, xml_filename) # Check if weights already exist bin_exists = os.path.exists(bin_path) xml_exists = os.path.exists(xml_path) if not bin_exists or not xml_exists: # If weights does not exist try: bin_success, bin_message, bin_path = download_file( source_url=bin_url, filename=bin_filename, folder=folder) xml_success, xml_message, xml_path = download_file( source_url=xml_url, filename=xml_filename, folder=folder) except Exception as e: logging.error(f"Failed to Download Weights. Error: {e}") logging.info(f"The Program will exit.") exit(1) else: # If weights exists return ( xml_path, f"Found existing weights. Skipping download.", ) # If downloading fails, exit the program if not bin_success or not xml_success: logging.error( f"Failed to Download Weights. Messages: bin_message: {bin_message} | xml_message: {xml_message}" ) logging.info(f"The Program will exit.") exit(1) return ( xml_path, f"Weights Downloaded Successfully. Messages: bin_message: {bin_message} | xml_message: {xml_message}", )
def load_model( self, model, device, input_size, output_size, num_requests, cpu_extension=None, plugin=None, ): """ Loads a network and an image to the Inference Engine plugin. :param model: .xml file of pre trained model :param cpu_extension: extension for the CPU device :param device: Target device :param input_size: Number of input layers :param output_size: Number of output layers :param num_requests: Index of Infer request value. Limited to device capabilities. :param plugin: Plugin for specified device :return: Shape of input layer """ model_xml = model model_bin = os.path.splitext(model_xml)[0] + ".bin" # Plugin initialization for specified device # and load extensions library if specified if not plugin: log.info("Initializing plugin for {} device...".format(device)) self.plugin = IECore() # print("========== {} ==========".format(self.plugin.get_config("CPU", "CPU_THREADS_NUM"))) # self.plugin.set_config({"CPU_THREADS_NUM": "4"}, "CPU") # print("========== {} ==========".format(self.plugin.get_config("CPU", "CPU_THREADS_NUM"))) # print("=="*10) # print("========== {} ==========".format(self.plugin.get_config("CPU", "CPU_BIND_THREAD"))) else: self.plugin = plugin if cpu_extension and "CPU" in device: self.plugin.add_extension(cpu_extension, "CPU") # Read IR log.info("Reading IR...") self.net = IENetwork(model=model_xml, weights=model_bin) log.info("Loading IR to the plugin...") if device == "CPU": supported_layers = self.plugin.query_network(self.net, "CPU") not_supported_layers = [ l for l in self.net.layers.keys() if l not in supported_layers ] if len(not_supported_layers) != 0: log.error( "Following layers are not supported by " "the plugin for specified device {}:\n {}".format( device, ", ".join(not_supported_layers) ) ) log.error( "Please try to specify cpu extensions library path" " in command line parameters using -l " "or --cpu_extension command line argument" ) sys.exit(1) if num_requests == 0: # Loads network read from IR to theplugin self.net_plugin = self.plugin.load_network( network=self.net, device_name=device ) else: self.net_plugin = self.plugin.load_network( network=self.net, num_requests=num_requests, device_name=device ) self.input_blob = next(iter(self.net.inputs)) self.out_blob = next(iter(self.net.outputs)) return self.plugin, self.get_input_shape()
# If frame is not received if frame is None and live_stream: logging.warning("Broken Stream, attempting to reconnect...") time.sleep(30) cap = VideoStream(video_source).start() continue elif frame is None and not live_stream: break original_frame = frame.copy() try: # Run Face Detection boxes = face_detector.detect(frame) except Exception as e: logging.error(f"Failed to detect: {e}") boxes = [] # Blur Faces for x1, y1, x2, y2 in boxes: face = frame[y1:y2, x1:x2] blurred_face = blur_frame(face, kernel_size=config.get("blur_strength", 99)) frame[y1:y2, x1:x2] = blurred_face # Calculate FPS frame, fps = calc_fps(start_time, frame) # To display and/or write video side by side, # with the original on the left and processed on the right if config.get("stacked_video", False):