Skip to content

Commit

Permalink
style: apply flake8 code style fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
CVHub520 committed Sep 21, 2024
1 parent 664829e commit e0d71c4
Show file tree
Hide file tree
Showing 56 changed files with 601 additions and 363 deletions.
7 changes: 5 additions & 2 deletions anylabeling/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import logging

import sys

sys.path.append(".")

import yaml
Expand Down Expand Up @@ -125,7 +126,7 @@ def main():
help="epsilon to find nearest vertex on canvas",
default=argparse.SUPPRESS,
)
args = parser.parse_args()
args = parser.parse_args()

if hasattr(args, "flags"):
if os.path.isfile(args.flags):
Expand Down Expand Up @@ -155,7 +156,9 @@ def main():
config_file_or_yaml = config_from_args.pop("config")
logger_level = config_from_args.pop("logger_level")
logger.setLevel(getattr(logging, logger_level.upper()))
logger.info(f"🚀 {gradient_text(f'X-AnyLabeling v{__version__} launched!')}")
logger.info(
f"🚀 {gradient_text(f'X-AnyLabeling v{__version__} launched!')}"
)
logger.info(f"⭐ If you like it, give us a star: {__url__}")
anylabeling_config.current_config_file = config_file_or_yaml
config = get_config(config_file_or_yaml, config_from_args, show_msg=True)
Expand Down
2 changes: 1 addition & 1 deletion anylabeling/app_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
__appdescription__ = "Advanced Auto Labeling Solution with Added Features"
__version__ = "2.4.2"
__preferred_device__ = "CPU" # GPU or CPU
__url__ = "https://github.com/CVHub520/X-AnyLabeling"
__url__ = "https://github.com/CVHub520/X-AnyLabeling"
10 changes: 5 additions & 5 deletions anylabeling/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
indent_text,
)

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)

if __name__ == "__main__":
Expand All @@ -19,11 +19,11 @@
}
system_info, pkg_info = collect_system_info()

logger.info(format_color(format_bold("Application Information:"), '36'))
logger.info(format_color(format_bold("Application Information:"), "36"))
logger.info(indent_text(pprint.pformat(app_info)))

logger.info(format_color(format_bold("\nSystem Information:"), '36'))
logger.info(format_color(format_bold("\nSystem Information:"), "36"))
logger.info(indent_text(pprint.pformat(system_info)))

logger.info(format_color(format_bold("\nPackage Information:"), '36'))
logger.info(indent_text(pprint.pformat(pkg_info)))
logger.info(format_color(format_bold("\nPackage Information:"), "36"))
logger.info(indent_text(pprint.pformat(pkg_info)))
17 changes: 13 additions & 4 deletions anylabeling/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

current_config_file = None


def update_dict(target_dict, new_dict, validate_item=None):
for key, value in new_dict.items():
if validate_item:
Expand Down Expand Up @@ -68,7 +69,9 @@ def validate_config_item(key, value):
)


def get_config(config_file_or_yaml=None, config_from_args=None, show_msg=False):
def get_config(
config_file_or_yaml=None, config_from_args=None, show_msg=False
):
# 1. Load default configuration
config = get_default_config()

Expand All @@ -82,12 +85,18 @@ def get_config(config_file_or_yaml=None, config_from_args=None, show_msg=False):
config_from_yaml = yaml.safe_load(f)
update_dict(config, config_from_yaml, validate_item=validate_config_item)
if show_msg:
logger.info(f"🔧️ Initializing config from local file: {config_file_or_yaml}")
logger.info(
f"🔧️ Initializing config from local file: {config_file_or_yaml}"
)

# 3. Update configuration with command line arguments
if config_from_args:
update_dict(config, config_from_args, validate_item=validate_config_item)
update_dict(
config, config_from_args, validate_item=validate_config_item
)
if show_msg:
logger.info(f"🔄 Updated config from CLI arguments: {config_from_args}")
logger.info(
f"🔄 Updated config from CLI arguments: {config_from_args}"
)

return config
3 changes: 3 additions & 0 deletions anylabeling/resources/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -18226,10 +18226,13 @@
rcc_version = 2
qt_resource_struct = qt_resource_struct_v2


def qInitResources():
QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)


def qCleanupResources():
QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)


qInitResources()
47 changes: 3 additions & 44 deletions anylabeling/services/auto_labeling/__base__/rtmdet.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

"""
The onnxruntime demo of the RTMDet model
Ref:
Ref:
https://github.com/open-mmlab/mmyolo/tree/dev/configs/rtmdet
https://platform.openmmlab.com/deploee/onnx-detail?search=rtmdet&tag=&page=1
https://github.com/Tau-J/rtmlib/blob/main/rtmlib/tools/object_detection/rtmdet.py
Expand Down Expand Up @@ -122,50 +122,9 @@ def postprocess(

if outputs.shape[-1] == 4:
# onnx without nms module

grids = []
expanded_strides = []
strides = [8, 16, 32]

hsizes = [self.model_input_size[0] // stride for stride in strides]
wsizes = [self.model_input_size[1] // stride for stride in strides]

for hsize, wsize, stride in zip(hsizes, wsizes, strides):
xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
grids.append(grid)
shape = grid.shape[:2]
expanded_strides.append(np.full((*shape, 1), stride))

grids = np.concatenate(grids, 1)
expanded_strides = np.concatenate(expanded_strides, 1)
outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides

predictions = outputs[0]
boxes = predictions[:, :4]
scores = predictions[:, 4:5] * predictions[:, 5:]

boxes_xyxy = np.ones_like(boxes)
boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
boxes_xyxy /= ratio
dets = multiclass_nms(
boxes_xyxy,
scores,
nms_thr=self.nms_thr,
score_thr=self.score_thr,
raise NotImplementedError(
"RTMDet without nms module is not supported yet."
)
if dets is not None:
pack_dets = (dets[:, :4], dets[:, 4], dets[:, 5])
final_boxes, final_scores, final_cls_inds = pack_dets
isscore = final_scores > 0.3
iscat = final_cls_inds == 0
isbbox = [i and j for (i, j) in zip(isscore, iscat)]
final_boxes = final_boxes[isbbox]

elif outputs.shape[-1] == 5:
# onnx contains nms module
pack_dets = (outputs[0, :, :4], outputs[0, :, 4])
Expand Down
10 changes: 7 additions & 3 deletions anylabeling/services/auto_labeling/__base__/sam2.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ def __init__(self, path: str, device: str) -> None:
providers = ["CUDAExecutionProvider"]
sess_options = ort.SessionOptions()
sess_options.log_severity_level = 3
self.session = ort.InferenceSession(path, providers=providers, sess_options=sess_options)
self.session = ort.InferenceSession(
path, providers=providers, sess_options=sess_options
)

# Get model info
self.get_input_details()
Expand Down Expand Up @@ -158,10 +160,12 @@ def __init__(
# Initialize model
providers = ["CPUExecutionProvider"]
if device.lower() == "gpu":
providers = ["CUDAExecutionProvider"]
providers = ["CUDAExecutionProvider"]
sess_options = ort.SessionOptions()
sess_options.log_severity_level = 3
self.session = ort.InferenceSession(path, providers=providers, sess_options=sess_options)
self.session = ort.InferenceSession(
path, providers=providers, sess_options=sess_options
)

self.orig_im_size = (
orig_im_size if orig_im_size is not None else encoder_input_size
Expand Down
12 changes: 9 additions & 3 deletions anylabeling/services/auto_labeling/__base__/yolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,12 +406,16 @@ def predict_shapes(self, image, image_path=None):
zip(boxes, class_ids, scores, points, keypoints, track_ids)
):
if self.task == "det" or self.show_boxes:
shape = self.create_rectangle_shape(box, score, i, class_id, track_id)
shape = self.create_rectangle_shape(
box, score, i, class_id, track_id
)
shapes.append(shape)
if self.task == "seg":
if len(point) < 3:
continue
shape = self.create_polygon_shape(point, score, class_id, track_id)
shape = self.create_polygon_shape(
point, score, class_id, track_id
)
shapes.append(shape)
if self.task == "pose":
label = str(self.classes[int(class_id)])
Expand All @@ -428,7 +432,9 @@ def predict_shapes(self, image, image_path=None):
or s < self.kpt_thres
):
continue
shape = self.create_keypoint_shape((x, y), keypoint_name, s, j, i, track_id)
shape = self.create_keypoint_shape(
(x, y), keypoint_name, s, j, i, track_id
)
shapes.append(shape)
if self.task == "obb":
shape = self.create_obb_shape(box, score, class_id, track_id)
Expand Down
1 change: 0 additions & 1 deletion anylabeling/services/auto_labeling/efficientvit_sam.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,6 @@ def predict_shapes(self, image, filename=None) -> AutoLabelingResult:
image_embedding = cached_data
else:
cv_image = qt_img_to_rgb_cv_img(image, filename)
origin_image_size = cv_image.shape[:2]
if self.stop_inference:
return AutoLabelingResult([], replace=False)
image_embedding = self.encoder_model(cv_image)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@


class OnnxBaseModel:
def __init__(self, model_path, device_type: str = "cpu", log_severity_level: int = 0):
def __init__(
self, model_path, device_type: str = "cpu", log_severity_level: int = 3
):
self.sess_opts = ort.SessionOptions()
self.sess_opts.log_severity_level = log_severity_level
if "OMP_NUM_THREADS" in os.environ:
Expand Down
2 changes: 1 addition & 1 deletion anylabeling/services/auto_labeling/grounding_sam2.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def __init__(self, model_config, on_message) -> None:
raise FileNotFoundError(
QCoreApplication.translate(
"Model",
f"Could not download or initialize encoder of SAM2.",
"Could not download or initialize encoder of SAM2.",
)
)
decoder_model_abs_path = self.get_model_abs_path(
Expand Down
2 changes: 1 addition & 1 deletion anylabeling/services/auto_labeling/internimage_cls.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __init__(self, model_config, on_message) -> None:
raise FileNotFoundError(
QCoreApplication.translate(
"Model",
f"Could not download or initialize InternImage model.",
"Could not download or initialize InternImage model.",
)
)
self.net = OnnxBaseModel(model_abs_path, __preferred_device__)
Expand Down
4 changes: 1 addition & 3 deletions anylabeling/services/auto_labeling/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,7 @@ def get_filename_from_url(url):
ellipsis_download_url = (
download_url[:20] + "..." + download_url[-20:]
)
logger.info(
f"Downloading {ellipsis_download_url} to {model_abs_path}"
)
logger.info(f"Downloading {ellipsis_download_url} to {model_abs_path}")
try:
# Download and show progress
def _progress(count, block_size, total_size):
Expand Down
Loading

0 comments on commit e0d71c4

Please sign in to comment.