diff --git a/model_api/python/model_api/adapters/onnx_adapter.py b/model_api/python/model_api/adapters/onnx_adapter.py index 6d03380b..3ddec73b 100644 --- a/model_api/python/model_api/adapters/onnx_adapter.py +++ b/model_api/python/model_api/adapters/onnx_adapter.py @@ -42,11 +42,11 @@ def __init__(self, model: str, ort_options: dict = {}): loaded_model = onnx.load(model) inferred_model = SymbolicShapeInference.infer_shapes( - loaded_model, - int(sys.maxsize / 2), - False, - False, - False, + in_mp=loaded_model, + int_max=int(sys.maxsize / 2), + auto_merge=False, + guess_output_rank=False, + verbose=False, ) self.session = ort.InferenceSession( diff --git a/model_api/python/model_api/adapters/openvino_adapter.py b/model_api/python/model_api/adapters/openvino_adapter.py index 2e6b51ea..74593a04 100644 --- a/model_api/python/model_api/adapters/openvino_adapter.py +++ b/model_api/python/model_api/adapters/openvino_adapter.py @@ -233,8 +233,7 @@ def get_input_layers(self): input_layout, input.get_element_type().get_type_name(), ) - inputs = self._get_meta_from_ngraph(inputs) - return inputs + return self._get_meta_from_ngraph(inputs) def get_layout_for_input(self, input, shape=None) -> str: input_layout = "" @@ -263,8 +262,7 @@ def get_output_layers(self): list(output_shape), precision=output.get_element_type().get_type_name(), ) - outputs = self._get_meta_from_ngraph(outputs) - return outputs + return self._get_meta_from_ngraph(outputs) def reshape_model(self, new_shape): new_shape = { diff --git a/model_api/python/model_api/adapters/utils.py b/model_api/python/model_api/adapters/utils.py index 042b069b..fe403595 100644 --- a/model_api/python/model_api/adapters/utils.py +++ b/model_api/python/model_api/adapters/utils.py @@ -273,7 +273,7 @@ def crop_resize_graph(input: Output, size): target_size = list(size) target_size.reverse() - resized_image = opset.interpolate( + return opset.interpolate( cropped_frame, target_size, scales=np.array([0.0, 0.0], dtype=np.float32), @@ -281,7 +281,6 @@ def crop_resize_graph(input: Output, size): mode="linear", shape_calculation_mode="sizes", ) - return resized_image def resize_image_graph( diff --git a/model_api/python/model_api/models/anomaly.py b/model_api/python/model_api/models/anomaly.py index 598cd905..a8529d89 100644 --- a/model_api/python/model_api/models/anomaly.py +++ b/model_api/python/model_api/models/anomaly.py @@ -126,8 +126,7 @@ def parameters(cls) -> dict: def _normalize(self, tensor: np.ndarray, threshold: float) -> np.ndarray: """Currently supports only min-max normalization.""" normalized = ((tensor - threshold) / self.normalization_scale) + 0.5 - normalized = np.clip(normalized, 0, 1) - return normalized + return np.clip(normalized, 0, 1) @staticmethod def _get_boxes(mask: np.ndarray) -> np.ndarray: diff --git a/model_api/python/model_api/models/classification.py b/model_api/python/model_api/models/classification.py index cddf09bb..a3f2eb80 100644 --- a/model_api/python/model_api/models/classification.py +++ b/model_api/python/model_api/models/classification.py @@ -8,6 +8,7 @@ import copy import json from collections import defaultdict +from pathlib import Path import numpy as np from openvino.preprocess import PrePostProcessor @@ -102,7 +103,7 @@ def __init__(self, inference_adapter: InferenceAdapter, configuration: dict = {} self.load() def _load_labels(self, labels_file): - with open(labels_file) as f: + with Path(labels_file).open() as f: labels = [] for s in f: begin_idx = s.find(" ") @@ -417,8 +418,7 @@ def get_predecessors(lbl, candidates): if new_lbl not in output_labels: output_labels.append(new_lbl) - output_predictions = [(self.label_to_idx[lbl], lbl, label_to_prob[lbl]) for lbl in sorted(output_labels)] - return output_predictions + return [(self.label_to_idx[lbl], lbl, label_to_prob[lbl]) for lbl in sorted(output_labels)] class ProbabilisticLabelsResolver(GreedyLabelsResolver): diff --git a/model_api/python/model_api/models/instance_segmentation.py b/model_api/python/model_api/models/instance_segmentation.py index 4e067878..ff39c55b 100644 --- a/model_api/python/model_api/models/instance_segmentation.py +++ b/model_api/python/model_api/models/instance_segmentation.py @@ -45,7 +45,7 @@ def parameters(cls): ) return parameters - def _get_outputs(self): + def _get_outputs(self): # noqa: C901 TODO: Fix this method to reduce complexity if self.is_segmentoly: return self._get_segmentoly_outputs() filtered_names = [] @@ -82,7 +82,7 @@ def _get_outputs(self): if len(outputs) == 3: _append_xai_names(self.outputs, outputs) return outputs - self.raise_error(f"Unexpected outputs: {self.outputs}") + return self.raise_error(f"Unexpected outputs: {self.outputs}") def _get_segmentoly_outputs(self): outputs = {} diff --git a/model_api/python/model_api/models/model.py b/model_api/python/model_api/models/model.py index a1361d95..9b065455 100644 --- a/model_api/python/model_api/models/model.py +++ b/model_api/python/model_api/models/model.py @@ -105,11 +105,9 @@ def get_model_class(cls, name): for subclass in subclasses: if name.lower() == subclass.__model__.lower(): return subclass - cls.raise_error( - 'There is no model with name "{}" in list: {}'.format( - name, - ", ".join([subclass.__model__ for subclass in subclasses]), - ), + return cls.raise_error( + f"There is no model with name {name} in list: " + f"{', '.join([subclass.__model__ for subclass in subclasses])}", ) @classmethod @@ -214,8 +212,7 @@ def parameters(cls): Returns: - the dictionary with defined wrapper data parameters """ - parameters = {} - return parameters + return {} def _load_config(self, config): """Reads the configuration and creates data attributes diff --git a/model_api/python/model_api/models/result_types.py b/model_api/python/model_api/models/result_types.py index 37f17006..d51c505c 100644 --- a/model_api/python/model_api/models/result_types.py +++ b/model_api/python/model_api/models/result_types.py @@ -243,5 +243,4 @@ def __str__(self): def _array_shape_to_str(array: np.ndarray | None) -> str: if array is not None: return f"[{','.join(str(i) for i in array.shape)}]" - else: - return "[]" + return "[]" diff --git a/model_api/python/model_api/models/segmentation.py b/model_api/python/model_api/models/segmentation.py index 3c08dbfe..5056b95c 100644 --- a/model_api/python/model_api/models/segmentation.py +++ b/model_api/python/model_api/models/segmentation.py @@ -209,14 +209,13 @@ def postprocess(self, outputs, meta): input_image_width = meta["original_shape"][1] result = outputs[self.output_blob_name].squeeze() result = 1 / (1 + np.exp(-result)) - result = cv2.resize( + return cv2.resize( result, (input_image_width, input_image_height), 0, 0, interpolation=cv2.INTER_NEAREST, ) - return result _feature_vector_name = "feature_vector" diff --git a/model_api/python/model_api/models/ssd.py b/model_api/python/model_api/models/ssd.py index bfe5fa05..ee6776c9 100644 --- a/model_api/python/model_api/models/ssd.py +++ b/model_api/python/model_api/models/ssd.py @@ -61,7 +61,8 @@ def _get_output_parser( return parser except ValueError: pass - self.raise_error("Unsupported model outputs") + msg = "Unsupported model outputs" + raise ValueError(msg) def _parse_outputs(self, outputs): return self.output_parser(outputs) @@ -156,8 +157,7 @@ def __call__(self, outputs): labels = np.full(len(bboxes), self.default_label, dtype=bboxes.dtype) labels = labels.squeeze(0) - detections = [Detection(*bbox, score, label) for label, score, bbox in zip(labels, scores, bboxes)] - return detections + return [Detection(*bbox, score, label) for label, score, bbox in zip(labels, scores, bboxes)] _bbox_area_threshold = 1.0 diff --git a/model_api/python/model_api/models/types.py b/model_api/python/model_api/models/types.py index 2f684fb0..37013f2e 100644 --- a/model_api/python/model_api/models/types.py +++ b/model_api/python/model_api/models/types.py @@ -29,6 +29,8 @@ def get_value(self, value): errors = self.validate(value) if len(errors) == 0: return value if value is not None else self.default_value + msg = "Encountered errors during validation." + raise ValueError(msg) def build_error(self) -> None: pass diff --git a/model_api/python/model_api/models/utils.py b/model_api/python/model_api/models/utils.py index 26c48f8c..98d9e09d 100644 --- a/model_api/python/model_api/models/utils.py +++ b/model_api/python/model_api/models/utils.py @@ -5,6 +5,8 @@ from __future__ import annotations # TODO: remove when Python3.9 support is dropped +from pathlib import Path + import cv2 import numpy as np @@ -88,7 +90,7 @@ def scale(self, inputs): def load_labels(label_file): - with open(label_file) as f: + with Path(label_file).open() as f: return [x.strip() for x in f] diff --git a/model_api/python/model_api/models/visual_prompting.py b/model_api/python/model_api/models/visual_prompting.py index 3cfcf85d..0eb5c282 100644 --- a/model_api/python/model_api/models/visual_prompting.py +++ b/model_api/python/model_api/models/visual_prompting.py @@ -551,8 +551,7 @@ def _polygon_to_mask( else: contour = [[int(point[0]), int(point[1])] for point in polygon] gt_mask = np.zeros((height, width), dtype=np.uint8) - gt_mask = cv2.drawContours(gt_mask, np.asarray([contour]), 0, 1, cv2.FILLED) - return gt_mask + return cv2.drawContours(gt_mask, np.asarray([contour]), 0, 1, cv2.FILLED) def _generate_masked_features( diff --git a/model_api/python/model_api/models/yolo.py b/model_api/python/model_api/models/yolo.py index 60ed0c12..2d950072 100644 --- a/model_api/python/model_api/models/yolo.py +++ b/model_api/python/model_api/models/yolo.py @@ -97,8 +97,7 @@ def permute_to_N_HWA_K(tensor, K, output_layout): N, _, H, W = tensor.shape tensor = tensor.reshape(N, -1, K, H, W) tensor = tensor.transpose(0, 3, 4, 1, 2) - tensor = tensor.reshape(N, -1, K) - return tensor + return tensor.reshape(N, -1, K) def sigmoid(x): @@ -194,8 +193,7 @@ def parameters(cls): def postprocess(self, outputs, meta): detections = self._parse_outputs(outputs, meta) detections = self._resize_detections(detections, meta) - detections = self._add_label_names(detections) - return detections + return self._add_label_names(detections) def _parse_yolo_region(self, predictions, input_size, params): # ------------------------------------------ Extracting layer parameters --------------------------------------- @@ -329,8 +327,7 @@ def _parse_outputs(self, outputs, meta): layer_params[1], ) - detections = self._filter(detections, self.iou_threshold) - return detections + return self._filter(detections, self.iou_threshold) class YoloV4(YOLO): @@ -680,8 +677,7 @@ def preprocess(self, inputs): def postprocess(self, outputs, meta): detections = self._parse_outputs(outputs) - detections = clip_detections(detections, meta["original_shape"]) - return detections + return clip_detections(detections, meta["original_shape"]) def _parse_outputs(self, outputs): boxes = outputs[self.bboxes_blob_name][0] @@ -716,9 +712,7 @@ def _parse_outputs(self, outputs): x_maxs = transposed_boxes[3] y_maxs = transposed_boxes[2] - detections = list(starmap(Detection, zip(x_mins, y_mins, x_maxs, y_maxs, out_scores, out_classes))) - - return detections + return list(starmap(Detection, zip(x_mins, y_mins, x_maxs, y_maxs, out_scores, out_classes))) class YOLOv5(DetectionModel): @@ -743,7 +737,7 @@ def parameters(cls): parameters = super().parameters() parameters["pad_value"].update_default_value(114) parameters["resize_type"].update_default_value("fit_to_window_letterbox") - parameters["reverse_input_channels"].update_default_value(True) + parameters["reverse_input_channels"].update_default_value(True) # noqa: FBT003 TODO: refactor this piece of code parameters["scale_values"].update_default_value([255.0]) parameters["confidence_threshold"].update_default_value(0.25) parameters.update( diff --git a/model_api/python/model_api/pipelines/async_pipeline.py b/model_api/python/model_api/pipelines/async_pipeline.py index 3c72b6b9..83dc974c 100644 --- a/model_api/python/model_api/pipelines/async_pipeline.py +++ b/model_api/python/model_api/pipelines/async_pipeline.py @@ -30,7 +30,7 @@ def callback(self, request, callback_args): preprocessing_meta, start_time, ) - except Exception as e: + except Exception as e: # noqa: BLE001 TODO: Figure out the exact exception that might be raised self.callback_exceptions.append(e) def submit_data(self, inputs, id, meta={}): diff --git a/model_api/python/model_api/tilers/detection.py b/model_api/python/model_api/tilers/detection.py index 8e4d5d77..624ca845 100644 --- a/model_api/python/model_api/tilers/detection.py +++ b/model_api/python/model_api/tilers/detection.py @@ -246,5 +246,4 @@ def _detection2array(detections): [[float(det.xmin), float(det.ymin), float(det.xmax), float(det.ymax)]], axis=0, ) - detections = np.concatenate((labels, scores, boxes), -1) - return detections + return np.concatenate((labels, scores, boxes), -1) diff --git a/model_api/python/pyproject.toml b/model_api/python/pyproject.toml index 064e9e96..c3628d22 100644 --- a/model_api/python/pyproject.toml +++ b/model_api/python/pyproject.toml @@ -93,41 +93,41 @@ lint.select = [ # "F", # Pyflakes (`F`) "E", # pycodestyle error (`E`) "W", # pycodestyle warning (`W`) - # "C90", # mccabe (`C90`) + "C90", # mccabe (`C90`) "I", # isort (`I`) # "N", # pep8-naming (`N`) # "D", # pydocstyle (`D`) # "UP", # pyupgrade (`UP`) # need min python version 3.10 - # "YTT", # flake8-2020 (`YTT`) + "YTT", # flake8-2020 (`YTT`) # "ANN", # flake8-annotations (`ANN`) - # "S", # flake8-bandit (`S`) - # "BLE", # flake8-blind-except (`BLE`) - # "FBT", # flake8-boolean-trap (`FBT`) + "S", # flake8-bandit (`S`) + "BLE", # flake8-blind-except (`BLE`) + "FBT", # flake8-boolean-trap (`FBT`) # "B", # flake8-bugbear (`B`) # "A", # flake8-builtins (`A`) "COM", # flake8-commas (`COM`) "CPY", # flake8-copyright (`CPY`) "C4", # flake8-comprehensions (`C4`) "DTZ", # flake8-datatimez (`DTZ`) - # "T10", # flake8-debugger (`T10`) + "T10", # flake8-debugger (`T10`) "EM", # flake8-errmsg (`EM`) # "FA", # flake8-future-annotations (`FA`) "ISC", # flake8-implicit-str-concat (`ISC`) "ICN", # flake8-import-conventions (`ICN`) - # "PIE", # flake8-pie (`PIE`) - # "PT", # flake8-pytest-style (`PT`) - # "RSE", # flake8-raise (`RSE`) - # "RET", # flake8-return (`RET`) + "PIE", # flake8-pie (`PIE`) + "PT", # flake8-pytest-style (`PT`) + "RSE", # flake8-raise (`RSE`) + "RET", # flake8-return (`RET`) "SLF", # flake8-self (`SLF`) "SIM", # flake8-simplify (`SIM`) "TID", # flake8-tidy-imports (`TID`) # "TCH", # flake8-type-checking (`TCH`) - # "INT", # flake8-gettext (`INT`) + "INT", # flake8-gettext (`INT`) # "ARG", # flake8-unsused-arguments (`ARG`) - # "PTH", # flake8-use-pathlib (`PTH`) + "PTH", # flake8-use-pathlib (`PTH`) # "TD", # flake8-todos (`TD`) # "FIX", # flake8-fixme (`FIX`) - # "ERA", # eradicate (`ERA`) + "ERA", # eradicate (`ERA`) "PD", # pandas-vet (`PD`) "PGH", # pygrep-hooks (`PGH`) # "PL", # pylint (`PL`)