Skip to content

Commit 65b3a4a

Browse files
enable pycodestyle
Signed-off-by: Ashwin Vaidya <[email protected]>
1 parent 23620d1 commit 65b3a4a

File tree

12 files changed

+77
-34
lines changed

12 files changed

+77
-34
lines changed

model_api/python/model_api/adapters/inference_adapter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from abc import ABC, abstractmethod
77
from dataclasses import dataclass, field
8-
from typing import Any, Dict, List, Set, Tuple
8+
from typing import Any
99

1010

1111
@dataclass

model_api/python/model_api/adapters/openvino_adapter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,9 +339,9 @@ def embed_preprocessing(
339339
ppp = PrePostProcessor(self.model)
340340

341341
# Change the input type to the 8-bit image
342-
if dtype == int:
342+
if dtype is int:
343343
ppp.input(input_idx).tensor().set_element_type(Type.u8)
344-
elif dtype == float:
344+
elif dtype is float:
345345
ppp.input(input_idx).tensor().set_element_type(Type.f32)
346346

347347
ppp.input(input_idx).tensor().set_layout(ov.Layout("NHWC")).set_color_format(

model_api/python/model_api/adapters/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import math
99
from functools import partial
10-
from typing import Callable, Optional
10+
from typing import Callable
1111

1212
import cv2
1313
import numpy as np

model_api/python/model_api/models/action_classification.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,10 @@ def parameters(cls) -> dict[str, Any]:
9999
description="Path to file with labels. Overrides the labels, if they sets via 'labels' parameter",
100100
),
101101
"mean_values": ListValue(
102-
description="Normalization values, which will be subtracted from image channels for image-input layer during preprocessing",
102+
description=(
103+
"Normalization values, which will be subtracted from image channels "
104+
"for image-input layer during preprocessing"
105+
),
103106
default_value=[],
104107
),
105108
"pad_value": NumericalValue(

model_api/python/model_api/models/classification.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,11 @@ def resolve_labels(self, predictions):
374374
"""
375375

376376
def get_predecessors(lbl, candidates):
377-
"""Returns all the predecessors of the input label or an empty list if one of the predecessors is not a candidate."""
377+
"""Return all predecessors.
378+
379+
Returns all the predecessors of the input label or an empty list if one of the predecessors is not a
380+
candidate.
381+
"""
378382
predecessors = []
379383

380384
last_parent = self.label_tree.get_parent(lbl)
@@ -517,7 +521,8 @@ def _resolve_exclusive_labels(
517521
For labels in `label_to_probability` sets labels that are most likely (maximum probability) in their exclusive
518522
group to 1.0 and other (non-max) labels to probability 0.
519523
"""
520-
# actual exclusive group selection should happen when extracting initial probs (apply argmax to exclusive groups)
524+
# actual exclusive group selection should happen when extracting initial probs
525+
# (apply argmax to exclusive groups)
521526
hard_classification = {}
522527
for label, probability in label_to_probability.items():
523528
hard_classification[label] = float(probability > 0.0)

model_api/python/model_api/models/image_model.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,10 @@ def parameters(cls):
9090
default_value=False,
9191
),
9292
"mean_values": ListValue(
93-
description="Normalization values, which will be subtracted from image channels for image-input layer during preprocessing",
93+
description=(
94+
"Normalization values, which will be subtracted from image "
95+
"channels for image-input layer during preprocessing"
96+
),
9497
default_value=[],
9598
),
9699
"orig_height": NumericalValue(

model_api/python/model_api/models/model.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import logging as log
77
import re
8-
from abc import ABC
98
from contextlib import contextmanager
109

1110
from model_api.adapters.inference_adapter import InferenceAdapter
@@ -135,9 +134,11 @@ def create_model(
135134
136135
Args:
137136
model (str): model name from OpenVINO Model Zoo, path to model, OVMS URL
138-
configuration (:obj:`dict`, optional): dictionary of model config with model properties, for example confidence_threshold, labels
137+
configuration (:obj:`dict`, optional): dictionary of model config with model properties, for example
138+
confidence_threshold, labels
139139
model_type (:obj:`str`, optional): name of model wrapper to create (e.g. "ssd")
140-
preload (:obj:`bool`, optional): whether to call load_model(). Can be set to false to reshape model before loading
140+
preload (:obj:`bool`, optional): whether to call load_model(). Can be set to false to reshape model before
141+
loading.
141142
core (optional): openvino.Core instance, passed to OpenvinoAdapter
142143
weights_path (:obj:`str`, optional): path to .bin file with model weights
143144
adaptor_parameters (:obj:`dict`, optional): parameters of ModelAdaptor
@@ -147,7 +148,8 @@ def create_model(
147148
max_num_requests (:obj:`int`, optional): number of infer requests for asynchronous inference
148149
precision (:obj:`str`, optional): inference precision (e.g. "FP16")
149150
download_dir (:obj:`str`, optional): directory where to store downloaded models
150-
cache_dir (:obj:`str`, optional): directory where to store compiled models to reduce the load time before the inference
151+
cache_dir (:obj:`str`, optional): directory where to store compiled models to reduce the load time before
152+
the inference.
151153
152154
Returns:
153155
Model object
@@ -482,11 +484,13 @@ def log_layers_info(self):
482484
"""Prints the shape, precision and layout for all model inputs/outputs."""
483485
for name, metadata in self.inputs.items():
484486
self.logger.info(
485-
f"\tInput layer: {name}, shape: {metadata.shape}, precision: {metadata.precision}, layout: {metadata.layout}",
487+
f"\tInput layer: {name}, shape: {metadata.shape}, "
488+
f"precision: {metadata.precision}, layout: {metadata.layout}",
486489
)
487490
for name, metadata in self.outputs.items():
488491
self.logger.info(
489-
f"\tOutput layer: {name}, shape: {metadata.shape}, precision: {metadata.precision}, layout: {metadata.layout}",
492+
f"\tOutput layer: {name}, shape: {metadata.shape}, "
493+
f"precision: {metadata.precision}, layout: {metadata.layout}",
490494
)
491495

492496
def save(self, xml_path, bin_path="", version="UNSPECIFIED"):

model_api/python/model_api/models/segmentation.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,10 @@ def parameters(cls):
9999
),
100100
"soft_threshold": NumericalValue(
101101
value_type=float,
102-
description="Probability threshold value for bounding box filtering. inf value means no blurring and no soft_threshold",
102+
description=(
103+
"Probability threshold value for bounding box filtering. "
104+
"inf value means no blurring and no soft_threshold"
105+
),
103106
default_value=float("-inf"),
104107
),
105108
"return_soft_prediction": BooleanValue(

model_api/python/model_api/models/utils.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@ class ClassificationResult(
4747
def __str__(self):
4848
labels = ", ".join(f"{idx} ({label}): {confidence:.3f}" for idx, label, confidence in self.top_labels)
4949
return (
50-
f"{labels}, [{','.join(str(i) for i in self.saliency_map.shape)}], [{','.join(str(i) for i in self.feature_vector.shape)}], "
50+
f"{labels}, "
51+
f"[{','.join(str(i) for i in self.saliency_map.shape)}], "
52+
f"[{','.join(str(i) for i in self.feature_vector.shape)}], "
5153
f"[{','.join(str(i) for i in self.raw_scores.shape)}]"
5254
)
5355

@@ -76,7 +78,9 @@ def __str__(self):
7678
obj_str = "; ".join(str(obj) for obj in self.objects)
7779
if obj_str:
7880
obj_str += "; "
79-
return f"{obj_str}[{','.join(str(i) for i in self.saliency_map.shape)}]; [{','.join(str(i) for i in self.feature_vector.shape)}]"
81+
saliency_map_shape = ",".join(str(i) for i in self.saliency_map.shape)
82+
feature_vector_shape = ",".join(str(i) for i in self.feature_vector.shape)
83+
return f"{obj_str}[{saliency_map_shape}]; [{feature_vector_shape}]"
8084

8185

8286
class SegmentedObject(Detection):
@@ -194,14 +198,18 @@ class DetectedKeypoints(NamedTuple):
194198
scores: np.ndarray
195199

196200
def __str__(self):
197-
return f"keypoints: {self.keypoints.shape}, keypoints_x_sum: {np.sum(self.keypoints[:, :1]):.3f}, scores: {self.scores.shape}"
201+
return (
202+
f"keypoints: {self.keypoints.shape}, "
203+
f"keypoints_x_sum: {np.sum(self.keypoints[:, :1]):.3f}, "
204+
f"scores: {self.scores.shape}"
205+
)
198206

199207

200208
def add_rotated_rects(segmented_objects):
201209
objects_with_rects = []
202210
for segmented_object in segmented_objects:
203211
mask = segmented_object.mask.astype(np.uint8)
204-
contours, hierarchies = cv2.findContours(
212+
contours, _ = cv2.findContours(
205213
mask,
206214
cv2.RETR_EXTERNAL,
207215
cv2.CHAIN_APPROX_SIMPLE,
@@ -269,7 +277,10 @@ def __str__(self):
269277
for i, count in enumerate(outHist):
270278
if count > 0:
271279
hist += f"{i}: {count[0] / self.resultImage.size:.3f}, "
272-
return f"{hist}[{','.join(str(i) for i in self.soft_prediction.shape)}], [{','.join(str(i) for i in self.saliency_map.shape)}], [{','.join(str(i) for i in self.feature_vector.shape)}]"
280+
soft_pred_shape = ",".join(str(i) for i in self.soft_prediction.shape)
281+
saliency_map_shape = ",".join(str(i) for i in self.saliency_map.shape)
282+
feature_vector_shape = ",".join(str(i) for i in self.feature_vector.shape)
283+
return f"{hist}[{soft_pred_shape}], " f"[{saliency_map_shape}], " f"[{feature_vector_shape}]"
273284

274285

275286
class DetectionWithLandmarks(Detection):

model_api/python/model_api/models/visual_prompting.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,8 @@ def __init__(
143143
encoder_model (SAMImageEncoder): initialized decoder wrapper
144144
decoder_model (SAMDecoder): initialized encoder wrapper
145145
reference_features (VisualPromptingFeatures | None, optional): Previously generated reference features.
146-
Once the features are passed, one can skip learn() method, and start predicting masks right away. Defaults to None.
146+
Once the features are passed, one can skip learn() method, and start predicting masks right away.
147+
Defaults to None.
147148
threshold (float, optional): Threshold to match vs reference features on infer(). Greater value means a
148149
stricter matching. Defaults to 0.65.
149150
"""
@@ -213,7 +214,8 @@ def learn(
213214
reset_features (bool, optional): Forces learning from scratch. Defaults to False.
214215
215216
Returns:
216-
tuple[VisualPromptingFeatures, np.ndarray]: return values are the updated VPT reference features and reference masks.
217+
tuple[VisualPromptingFeatures, np.ndarray]: return values are the updated VPT reference features and
218+
reference masks.
217219
The shape of the reference mask is N_labels x H x W, where H and W are the same as in the input image.
218220
"""
219221
if boxes is None and points is None and polygons is None:
@@ -317,26 +319,32 @@ def infer(
317319
318320
Args:
319321
image (np.ndarray): HWC-shaped image
320-
reference_features (VisualPromptingFeatures | None, optional): Reference features object obtained during previous learn() calls.
321-
If not passed, object internal state is used, which reflects the last learn() call. Defaults to None.
322-
apply_masks_refinement (bool, optional): Flag controlling additional refinement stage on inference. Once enabled, decoder will
323-
be launched 2 extra times to refine the masks obtained with the first decoder call. Defaults to True.
322+
reference_features (VisualPromptingFeatures | None, optional): Reference features object obtained during
323+
previous learn() calls. If not passed, object internal state is used, which reflects the last learn()
324+
call. Defaults to None.
325+
apply_masks_refinement (bool, optional): Flag controlling additional refinement stage on inference.
326+
Once enabled, decoder will be launched 2 extra times to refine the masks obtained with the first decoder
327+
call. Defaults to True.
324328
325329
Returns:
326-
ZSLVisualPromptingResult: Mapping label -> predicted mask. Each mask object contains a list of binary masks, and a list of
327-
related prompts. Each binary mask corresponds to one prompt point. Class mask can be obtained by applying OR operation to all
328-
mask corresponding to one label.
330+
ZSLVisualPromptingResult: Mapping label -> predicted mask. Each mask object contains a list of binary masks,
331+
and a list of related prompts. Each binary mask corresponds to one prompt point. Class mask can be
332+
obtained by applying OR operation to all mask corresponding to one label.
329333
"""
330334
if reference_features is None:
331335
if self._reference_features is None:
332336
raise RuntimeError(
333-
"Reference features are not defined. This parameter can be passed via SAMLearnableVisualPrompter constructor, or as an argument of infer() method",
337+
(
338+
"Reference features are not defined. This parameter can be passed via "
339+
"SAMLearnableVisualPrompter constructor, or as an argument of infer() method"
340+
),
334341
)
335342
reference_feats = self._reference_features
336343

337344
if self._used_indices is None:
338345
raise RuntimeError(
339-
"Used indices are not defined. This parameter can be passed via SAMLearnableVisualPrompter constructor, or as an argument of infer() method",
346+
"Used indices are not defined. This parameter can be passed via "
347+
"SAMLearnableVisualPrompter constructor, or as an argument of infer() method"
340348
)
341349
used_idx = self._used_indices
342350
else:

0 commit comments

Comments
 (0)