Skip to content

Commit

Permalink
Apply Ruff UP auto-fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Oct 1, 2024
1 parent e8fc77e commit dd0dcdf
Show file tree
Hide file tree
Showing 22 changed files with 48 additions and 57 deletions.
1 change: 0 additions & 1 deletion examples/bbox_detection/labelme2voc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python

from __future__ import print_function

import argparse
import glob
Expand Down
1 change: 0 additions & 1 deletion examples/instance_segmentation/labelme2voc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python

from __future__ import print_function

import argparse
import glob
Expand Down
1 change: 0 additions & 1 deletion examples/tutorial/load_label_png.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python

from __future__ import print_function

import os.path as osp

Expand Down
8 changes: 3 additions & 5 deletions labelme/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ def main():
parser.add_argument(
"--config",
dest="config",
help="config file or yaml-format string (default: {})".format(
default_config_file
),
help=f"config file or yaml-format string (default: {default_config_file})",
default=default_config_file,
)
# config for the gui
Expand Down Expand Up @@ -106,7 +104,7 @@ def main():
args = parser.parse_args()

if args.version:
print("{0} {1}".format(__appname__, __version__))
print(f"{__appname__} {__version__}")
sys.exit(0)

logger.setLevel(getattr(logging, args.logger_level.upper()))
Expand Down Expand Up @@ -173,7 +171,7 @@ def main():
)

if reset_config:
logger.info("Resetting Qt config: %s" % win.settings.fileName())
logger.info("Resetting Qt config: %s", win.settings.fileName())
win.settings.clear()
sys.exit(0)

Expand Down
16 changes: 7 additions & 9 deletions labelme/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import functools
import html
import math
Expand Down Expand Up @@ -962,7 +960,7 @@ def setDirty(self):
self.actions.save.setEnabled(True)
title = __appname__
if self.filename is not None:
title = "{} - {}*".format(title, self.filename)
title = f"{title} - {self.filename}*"
self.setWindowTitle(title)

def setClean(self):
Expand All @@ -978,7 +976,7 @@ def setClean(self):
self.actions.createAiMaskMode.setEnabled(True)
title = __appname__
if self.filename is not None:
title = "{} - {}".format(title, self.filename)
title = f"{title} - {self.filename}"
self.setWindowTitle(title)

if self.hasLabelFile():
Expand Down Expand Up @@ -1251,7 +1249,7 @@ def _edit_label(self, value=None):
)
)
else:
item.setText("{} ({})".format(shape.label, shape.group_id))
item.setText(f"{shape.label} ({shape.group_id})")
self.setDirty()
if self.uniqLabelList.findItemByLabel(shape.label) is None:
item = self.uniqLabelList.createItemFromLabel(shape.label)
Expand Down Expand Up @@ -1304,7 +1302,7 @@ def addLabel(self, shape):
if shape.group_id is None:
text = shape.label
else:
text = "{} ({})".format(shape.label, shape.group_id)
text = f"{shape.label} ({shape.group_id})"
label_list_item = LabelListWidgetItem(text, shape)
self.labelList.addItem(label_list_item)
if self.uniqLabelList.findItemByLabel(shape.label) is None:
Expand Down Expand Up @@ -1693,7 +1691,7 @@ def loadFile(self, filename=None):

if image.isNull():
formats = [
"*.{}".format(fmt.data().decode())
f"*.{fmt.data().decode()}"
for fmt in QtGui.QImageReader.supportedImageFormats()
]
self.errorMessage(
Expand Down Expand Up @@ -1902,7 +1900,7 @@ def openFile(self, _value=False):
return
path = osp.dirname(str(self.filename)) if self.filename else "."
formats = [
"*.{}".format(fmt.data().decode())
f"*.{fmt.data().decode()}"
for fmt in QtGui.QImageReader.supportedImageFormats()
]
filters = self.tr("Image & Label files (%s)") % " ".join(
Expand Down Expand Up @@ -2035,7 +2033,7 @@ def deleteFile(self):
label_file = self.getLabelFile()
if osp.exists(label_file):
os.remove(label_file)
logger.info("Label file is removed: {}".format(label_file))
logger.info(f"Label file is removed: {label_file}")

item = self.fileListWidget.currentItem()
item.setCheckState(Qt.Unchecked)
Expand Down
8 changes: 4 additions & 4 deletions labelme/cli/draw_label_png.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ def main():

unique_label_values = np.unique(label)

logger.info("Label image shape: {}".format(label.shape))
logger.info("Label values: {}".format(unique_label_values.tolist()))
logger.info(f"Label image shape: {label.shape}")
logger.info(f"Label values: {unique_label_values.tolist()}")
if label_names is not None:
logger.info(
"Label names: {}".format(
[
"{}:{}".format(label_value, label_names[label_value])
f"{label_value}:{label_names[label_value]}"
for label_value in unique_label_values
]
)
Expand Down Expand Up @@ -75,7 +75,7 @@ def main():
label_names=label_names,
font_size=label.shape[1] // 30,
)
plt.title("{}\n{}".format(args.label_png, args.image))
plt.title(f"{args.label_png}\n{args.image}")
plt.imshow(label_viz_with_overlay)

plt.tight_layout()
Expand Down
2 changes: 1 addition & 1 deletion labelme/cli/export_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def main():
for lbl_name in label_names:
f.write(lbl_name + "\n")

logger.info("Saved to: {}".format(out_dir))
logger.info(f"Saved to: {out_dir}")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion labelme/cli/json_to_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def main():
for lbl_name in label_names:
f.write(lbl_name + "\n")

logger.info("Saved to: {}".format(out_dir))
logger.info(f"Saved to: {out_dir}")


if __name__ == "__main__":
Expand Down
7 changes: 3 additions & 4 deletions labelme/cli/on_docker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python

from __future__ import print_function

import argparse
import distutils.spawn
Expand Down Expand Up @@ -63,10 +62,10 @@ def labelme_on_docker(in_file, out_file):
if out_file:
out_file_a = osp.abspath(out_file)
out_file_b = osp.join("/home/developer", osp.basename(out_file))
cmd += " -v {0}:{1}".format(out_file_a, out_file_b)
cmd += " wkentaro/labelme labelme {0}".format(in_file_b)
cmd += f" -v {out_file_a}:{out_file_b}"
cmd += f" wkentaro/labelme labelme {in_file_b}"
if out_file:
cmd += " -O {0}".format(out_file_b)
cmd += f" -O {out_file_b}"
subprocess.call(shlex.split(cmd))

if out_file:
Expand Down
12 changes: 6 additions & 6 deletions labelme/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def update_dict(target_dict, new_dict, validate_item=None):
if validate_item:
validate_item(key, value)
if key not in target_dict:
logger.warn("Skipping unexpected key in config: {}".format(key))
logger.warn(f"Skipping unexpected key in config: {key}")
continue
if isinstance(target_dict[key], dict) and isinstance(value, dict):
update_dict(target_dict[key], value, validate_item=validate_item)
Expand All @@ -35,23 +35,23 @@ def get_default_config():
try:
shutil.copy(config_file, user_config_file)
except Exception:
logger.warn("Failed to save config: {}".format(user_config_file))
logger.warn(f"Failed to save config: {user_config_file}")

return config


def validate_config_item(key, value):
if key == "validate_label" and value not in [None, "exact"]:
raise ValueError(
"Unexpected value for config key 'validate_label': {}".format(value)
f"Unexpected value for config key 'validate_label': {value}"
)
if key == "shape_color" and value not in [None, "auto", "manual"]:
raise ValueError(
"Unexpected value for config key 'shape_color': {}".format(value)
f"Unexpected value for config key 'shape_color': {value}"
)
if key == "labels" and value is not None and len(value) != len(set(value)):
raise ValueError(
"Duplicates are detected for config key 'labels': {}".format(value)
f"Duplicates are detected for config key 'labels': {value}"
)


Expand All @@ -64,7 +64,7 @@ def get_config(config_file_or_yaml=None, config_from_args=None):
config_from_yaml = yaml.safe_load(config_file_or_yaml)
if not isinstance(config_from_yaml, dict):
with open(config_from_yaml) as f:
logger.info("Loading config file from: {}".format(config_from_yaml))
logger.info(f"Loading config file from: {config_from_yaml}")
config_from_yaml = yaml.safe_load(f)
update_dict(config, config_from_yaml, validate_item=validate_config_item)

Expand Down
9 changes: 5 additions & 4 deletions labelme/label_file.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import builtins
import contextlib
import io
import json
Expand All @@ -23,15 +24,15 @@ def open(name, mode):
encoding = None
else:
encoding = "utf-8"
yield io.open(name, mode, encoding=encoding)
yield builtins.open(name, mode, encoding=encoding)
return


class LabelFileError(Exception):
pass


class LabelFile(object):
class LabelFile:
suffix = ".json"

def __init__(self, filename=None):
Expand All @@ -46,8 +47,8 @@ def __init__(self, filename=None):
def load_image_file(filename):
try:
image_pil = PIL.Image.open(filename)
except IOError:
logger.error("Failed opening image file: {}".format(filename))
except OSError:
logger.error(f"Failed opening image file: {filename}")
return

# apply orientation to image according to exif
Expand Down
2 changes: 1 addition & 1 deletion labelme/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def colored(text):
attrs={"bold": True},
)

record.levelname2 = colored("{:<7}".format(record.levelname))
record.levelname2 = colored(f"{record.levelname:<7}")
record.message2 = colored(record.msg)

asctime2 = datetime.datetime.fromtimestamp(record.created)
Expand Down
4 changes: 2 additions & 2 deletions labelme/shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# - [opt] Store paths instead of creating new ones at each paint.


class Shape(object):
class Shape:
# Render handles as squares
P_SQUARE = 0

Expand Down Expand Up @@ -112,7 +112,7 @@ def shape_type(self, value):
"points",
"mask",
]:
raise ValueError("Unexpected shape_type: {}".format(value))
raise ValueError(f"Unexpected shape_type: {value}")
self._shape_type = value

def close(self):
Expand Down
2 changes: 1 addition & 1 deletion labelme/utils/qt.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def labelValidator():
return QtGui.QRegExpValidator(QtCore.QRegExp(r"^[^ \t].+"), None)


class struct(object):
class struct:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

Expand Down
4 changes: 2 additions & 2 deletions labelme/utils/shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,10 @@ def labelme_shapes_to_label(img_shape, shapes):

def masks_to_bboxes(masks):
if masks.ndim != 3:
raise ValueError("masks.ndim must be 3, but it is {}".format(masks.ndim))
raise ValueError(f"masks.ndim must be 3, but it is {masks.ndim}")
if masks.dtype != bool:
raise ValueError(
"masks.dtype must be bool type, but it is {}".format(masks.dtype)
f"masks.dtype must be bool type, but it is {masks.dtype}"
)
bboxes = []
for mask in masks:
Expand Down
2 changes: 1 addition & 1 deletion labelme/widgets/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, *args, **kwargs):
self.double_click = kwargs.pop("double_click", "close")
if self.double_click not in [None, "close"]:
raise ValueError(
"Unexpected value for double_click event: {}".format(self.double_click)
f"Unexpected value for double_click event: {self.double_click}"
)
self.num_backups = kwargs.pop("num_backups", 10)
self._crosshair = kwargs.pop(
Expand Down
2 changes: 1 addition & 1 deletion labelme/widgets/file_dialog_preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, *args, **kwargs):

def onChange(self, path):
if path.lower().endswith(".json"):
with open(path, "r") as f:
with open(path) as f:
data = json.load(f)
self.labelPreview.setText(json.dumps(data, indent=4, sort_keys=False))
self.labelPreview.label.setAlignment(
Expand Down
4 changes: 2 additions & 2 deletions labelme/widgets/label_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def __init__(
completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
completer.setFilterMode(QtCore.Qt.MatchContains)
else:
raise ValueError("Unsupported completion: {}".format(completion))
raise ValueError(f"Unsupported completion: {completion}")
completer.setModel(self.labelList.model())
self.edit.setCompleter(completer)

Expand Down Expand Up @@ -230,7 +230,7 @@ def popUp(self, text=None, move=True, flags=None, group_id=None, description=Non
items = self.labelList.findItems(text, QtCore.Qt.MatchFixedString)
if items:
if len(items) != 1:
logger.warning("Label list has duplicate '{}'".format(text))
logger.warning(f"Label list has duplicate '{text}'")
self.labelList.setCurrentItem(items[0])
row = self.labelList.row(items[0])
self.edit.completer().setCurrentRow(row)
Expand Down
4 changes: 2 additions & 2 deletions labelme/widgets/label_list_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def __hash__(self):
return id(self)

def __repr__(self):
return '{}("{}")'.format(self.__class__.__name__, self.text())
return f'{self.__class__.__name__}("{self.text()}")'


class StandardItemModel(QtGui.QStandardItemModel):
Expand Down Expand Up @@ -171,7 +171,7 @@ def findItemByShape(self, shape):
item = self.model().item(row, 0)
if item.shape() == shape:
return item
raise ValueError("cannot find shape: {}".format(shape))
raise ValueError(f"cannot find shape: {shape}")

def clear(self):
self.model().clear()
5 changes: 2 additions & 3 deletions labelme/widgets/unique_label_qlist_widget.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- encoding: utf-8 -*-

import html

Expand All @@ -22,7 +21,7 @@ def findItemByLabel(self, label):

def createItemFromLabel(self, label):
if self.findItemByLabel(label):
raise ValueError("Item for label '{}' already exists".format(label))
raise ValueError(f"Item for label '{label}' already exists")

item = QtWidgets.QListWidgetItem()
item.setData(Qt.UserRole, label)
Expand All @@ -31,7 +30,7 @@ def createItemFromLabel(self, label):
def setItemLabel(self, item, label, color=None):
qlabel = QtWidgets.QLabel()
if color is None:
qlabel.setText("{}".format(label))
qlabel.setText(f"{label}")
else:
qlabel.setText(
'{} <font color="#{:02x}{:02x}{:02x}">●</font>'.format(
Expand Down
Loading

0 comments on commit dd0dcdf

Please sign in to comment.