Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions model_api/python/model_api/adapters/onnx_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 2 additions & 4 deletions model_api/python/model_api/adapters/openvino_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand Down Expand Up @@ -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 = {
Expand Down
3 changes: 1 addition & 2 deletions model_api/python/model_api/adapters/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,15 +273,14 @@ 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),
axes=[h_axis, w_axis],
mode="linear",
shape_calculation_mode="sizes",
)
return resized_image


def resize_image_graph(
Expand Down
3 changes: 1 addition & 2 deletions model_api/python/model_api/models/anomaly.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions model_api/python/model_api/models/classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(" ")
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions model_api/python/model_api/models/instance_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down Expand Up @@ -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 = {}
Expand Down
11 changes: 4 additions & 7 deletions model_api/python/model_api/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions model_api/python/model_api/models/result_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "[]"
3 changes: 1 addition & 2 deletions model_api/python/model_api/models/segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 3 additions & 3 deletions model_api/python/model_api/models/ssd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions model_api/python/model_api/models/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion model_api/python/model_api/models/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]


Expand Down
3 changes: 1 addition & 2 deletions model_api/python/model_api/models/visual_prompting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
18 changes: 6 additions & 12 deletions model_api/python/model_api/models/yolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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 ---------------------------------------
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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):
Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion model_api/python/model_api/pipelines/async_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={}):
Expand Down
3 changes: 1 addition & 2 deletions model_api/python/model_api/tilers/detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
26 changes: 13 additions & 13 deletions model_api/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
Loading