diff --git a/labelme/app.py b/labelme/app.py index 4c9dbf414..4706b0324 100644 --- a/labelme/app.py +++ b/labelme/app.py @@ -86,7 +86,7 @@ def __init__( # Set point size from config file Shape.point_size = self._config["shape"]["point_size"] - super(MainWindow, self).__init__() + super().__init__() self.setWindowTitle(__appname__) # Whether we need to save or not. @@ -912,7 +912,7 @@ def menu(self, title, actions=None): def toolbar(self, title, actions=None): toolbar = ToolBar(title) - toolbar.setObjectName("%sToolBar" % title) + toolbar.setObjectName(f"{title}ToolBar") # toolbar.setOrientation(Qt.Vertical) toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) if actions: @@ -1771,7 +1771,7 @@ def resizeEvent(self, event): and self.zoomMode != self.MANUAL_ZOOM ): self.adjustScale() - super(MainWindow, self).resizeEvent(event) + super().resizeEvent(event) def paintCanvas(self): assert not self.image.isNull(), "cannot paint null image" @@ -1819,7 +1819,7 @@ def closeEvent(self, event): def dragEnterEvent(self, event): extensions = [ - ".%s" % fmt.data().decode().lower() + f".{fmt.data().decode().lower()}" for fmt in QtGui.QImageReader.supportedImageFormats() ] if event.mimeData().hasUrls(): @@ -1904,7 +1904,7 @@ def openFile(self, _value=False): for fmt in QtGui.QImageReader.supportedImageFormats() ] filters = self.tr("Image & Label files (%s)") % " ".join( - formats + ["*%s" % LabelFile.suffix] + formats + [f"*{LabelFile.suffix}"] ) fileDialog = FileDialogPreview(self) fileDialog.setFileMode(FileDialogPreview.ExistingFile) @@ -2033,7 +2033,7 @@ def deleteFile(self): label_file = self.getLabelFile() if osp.exists(label_file): os.remove(label_file) - logger.info(f"Label file is removed: {label_file}") + logger.info("Label file is removed: %s", label_file) item = self.fileListWidget.currentItem() item.setCheckState(Qt.Unchecked) @@ -2079,7 +2079,7 @@ def mayContinue(self): def errorMessage(self, title, message): return QtWidgets.QMessageBox.critical( - self, title, "

%s

%s" % (title, message) + self, title, f"

{title}

{message}" ) def currentPath(self): @@ -2155,7 +2155,7 @@ def imageList(self): def importDroppedImageFiles(self, imageFiles): extensions = [ - ".%s" % fmt.data().decode().lower() + f".{fmt.data().decode().lower()}" for fmt in QtGui.QImageReader.supportedImageFormats() ] @@ -2214,7 +2214,7 @@ def importDirImages(self, dirpath, pattern=None, load=True): def scanAllImages(self, folderPath): extensions = [ - ".%s" % fmt.data().decode().lower() + f".{fmt.data().decode().lower()}" for fmt in QtGui.QImageReader.supportedImageFormats() ] diff --git a/labelme/cli/draw_label_png.py b/labelme/cli/draw_label_png.py index 19360674e..ee28d52e1 100644 --- a/labelme/cli/draw_label_png.py +++ b/labelme/cli/draw_label_png.py @@ -41,17 +41,14 @@ def main(): unique_label_values = np.unique(label) - logger.info(f"Label image shape: {label.shape}") - logger.info(f"Label values: {unique_label_values.tolist()}") + logger.info("Label image shape: %s", label.shape) + logger.info("Label values: %s", unique_label_values.tolist()) if label_names is not None: - logger.info( - "Label names: {}".format( - [ - f"{label_value}:{label_names[label_value]}" - for label_value in unique_label_values - ] - ) - ) + names = [ + f"{label_value}:{label_names[label_value]}" + for label_value in unique_label_values + ] + logger.info("Label names: %s", names) if args.image: num_cols = 2 diff --git a/labelme/cli/export_json.py b/labelme/cli/export_json.py index f487982d0..8e3cb7dde 100644 --- a/labelme/cli/export_json.py +++ b/labelme/cli/export_json.py @@ -63,7 +63,7 @@ def main(): for lbl_name in label_names: f.write(lbl_name + "\n") - logger.info(f"Saved to: {out_dir}") + logger.info("Saved to: %s", out_dir) if __name__ == "__main__": diff --git a/labelme/cli/json_to_dataset.py b/labelme/cli/json_to_dataset.py index 082171c6d..cc4eb261e 100644 --- a/labelme/cli/json_to_dataset.py +++ b/labelme/cli/json_to_dataset.py @@ -73,7 +73,7 @@ def main(): for lbl_name in label_names: f.write(lbl_name + "\n") - logger.info(f"Saved to: {out_dir}") + logger.info("Saved to: %s", out_dir) if __name__ == "__main__": diff --git a/labelme/cli/on_docker.py b/labelme/cli/on_docker.py index 1367ec249..3732b3426 100644 --- a/labelme/cli/on_docker.py +++ b/labelme/cli/on_docker.py @@ -34,13 +34,13 @@ def get_ip(): def labelme_on_docker(in_file, out_file): ip = get_ip() - cmd = "xhost + %s" % ip + cmd = f"xhost + {ip}" subprocess.check_output(shlex.split(cmd)) if out_file: out_file = osp.abspath(out_file) if osp.exists(out_file): - raise RuntimeError("File exists: %s" % out_file) + raise RuntimeError(f"File exists: {out_file}") else: open(osp.abspath(out_file), "w") @@ -91,7 +91,7 @@ def main(): try: out_file = labelme_on_docker(args.in_file, args.output) if out_file: - print("Saved to: %s" % out_file) + print(f"Saved to: {out_file}") except RuntimeError as e: sys.stderr.write(e.__str__() + "\n") sys.exit(1) diff --git a/labelme/config/__init__.py b/labelme/config/__init__.py index a7f3bd683..f4a633505 100644 --- a/labelme/config/__init__.py +++ b/labelme/config/__init__.py @@ -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(f"Skipping unexpected key in config: {key}") + logger.warn("Skipping unexpected key in config: %s", key) continue if isinstance(target_dict[key], dict) and isinstance(value, dict): update_dict(target_dict[key], value, validate_item=validate_item) @@ -35,24 +35,18 @@ def get_default_config(): try: shutil.copy(config_file, user_config_file) except Exception: - logger.warn(f"Failed to save config: {user_config_file}") + logger.warn("Failed to save config: %s", user_config_file) return config def validate_config_item(key, value): if key == "validate_label" and value not in [None, "exact"]: - raise ValueError( - f"Unexpected value for config key 'validate_label': {value}" - ) + raise ValueError(f"Unexpected value for config key 'validate_label': {value}") if key == "shape_color" and value not in [None, "auto", "manual"]: - raise ValueError( - f"Unexpected value for config key 'shape_color': {value}" - ) + raise ValueError(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( - f"Duplicates are detected for config key 'labels': {value}" - ) + raise ValueError(f"Duplicates are detected for config key 'labels': {value}") def get_config(config_file_or_yaml=None, config_from_args=None): @@ -64,7 +58,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(f"Loading config file from: {config_from_yaml}") + logger.info("Loading config file from: %s", config_from_yaml) config_from_yaml = yaml.safe_load(f) update_dict(config, config_from_yaml, validate_item=validate_config_item) diff --git a/labelme/label_file.py b/labelme/label_file.py index 572701dae..f6aba1a6c 100644 --- a/labelme/label_file.py +++ b/labelme/label_file.py @@ -48,7 +48,7 @@ def load_image_file(filename): try: image_pil = PIL.Image.open(filename) except OSError: - logger.error(f"Failed opening image file: {filename}") + logger.error("Failed opening image file: %r", filename) return # apply orientation to image according to exif diff --git a/labelme/utils/_io.py b/labelme/utils/_io.py index 9e97ef558..1b7fa681d 100644 --- a/labelme/utils/_io.py +++ b/labelme/utils/_io.py @@ -21,6 +21,6 @@ def lblsave(filename, lbl): lbl_pil.save(filename) else: raise ValueError( - "[%s] Cannot save the pixel-wise class label as PNG. " - "Please consider using the .npy format." % filename + f"[{filename}] Cannot save the pixel-wise class label as PNG. " + "Please consider using the .npy format." ) diff --git a/labelme/utils/qt.py b/labelme/utils/qt.py index 0e3d35abf..6db4f7f6d 100644 --- a/labelme/utils/qt.py +++ b/labelme/utils/qt.py @@ -11,7 +11,7 @@ def newIcon(icon): icons_dir = osp.join(here, "../icons") - return QtGui.QIcon(osp.join(":/", icons_dir, "%s.png" % icon)) + return QtGui.QIcon(osp.join(":/", icons_dir, f"{icon}.png")) def newButton(text, icon=None, slot=None): @@ -95,4 +95,4 @@ def distancetoline(point, line): def fmtShortcut(text): mod, key = text.split("+", 1) - return "%s+%s" % (mod, key) + return f"{mod}+{key}" diff --git a/labelme/widgets/brightness_contrast_dialog.py b/labelme/widgets/brightness_contrast_dialog.py index 47f5d8ec3..bb5725755 100644 --- a/labelme/widgets/brightness_contrast_dialog.py +++ b/labelme/widgets/brightness_contrast_dialog.py @@ -9,7 +9,7 @@ class BrightnessContrastDialog(QtWidgets.QDialog): _base_value = 50 def __init__(self, img, callback, parent=None): - super(BrightnessContrastDialog, self).__init__(parent) + super().__init__(parent) self.setModal(True) self.setWindowTitle("Brightness/Contrast") diff --git a/labelme/widgets/canvas.py b/labelme/widgets/canvas.py index ee4dc49cb..fb3e3d3fd 100644 --- a/labelme/widgets/canvas.py +++ b/labelme/widgets/canvas.py @@ -60,7 +60,7 @@ def __init__(self, *args, **kwargs): "ai_mask": False, }, ) - super(Canvas, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] @@ -125,18 +125,18 @@ def createMode(self, value): "ai_polygon", "ai_mask", ]: - raise ValueError("Unsupported createMode: %s" % value) + raise ValueError(f"Unsupported createMode: {value}") self._createMode = value def initializeAiModel(self, name): if name not in [model.name for model in labelme.ai.MODELS]: - raise ValueError("Unsupported ai model: %s" % name) + raise ValueError(f"Unsupported ai model: {name}") model = [model for model in labelme.ai.MODELS if model.name == name][0] if self._ai_model is not None and self._ai_model.name == model.name: - logger.debug("AI model is already initialized: %r" % model.name) + logger.debug("AI model is already initialized: %r", model.name) else: - logger.debug("Initializing AI model: %r" % model.name) + logger.debug("Initializing AI model: %r", model.name) self._ai_model = model() if self.pixmap is None: @@ -668,7 +668,7 @@ def deleteShape(self, shape): def paintEvent(self, event): if not self.pixmap: - return super(Canvas, self).paintEvent(event) + return super().paintEvent(event) p = self._painter p.begin(self) @@ -780,7 +780,7 @@ def transformPos(self, point): def offsetToCenter(self): s = self.scale - area = super(Canvas, self).size() + area = super().size() w, h = self.pixmap.width() * s, self.pixmap.height() * s aw, ah = area.width(), area.height() x = (aw - w) / (2 * s) if aw > w else 0 @@ -898,7 +898,7 @@ def sizeHint(self): def minimumSizeHint(self): if self.pixmap: return self.scale * self.pixmap.size() - return super(Canvas, self).minimumSizeHint() + return super().minimumSizeHint() def wheelEvent(self, ev): if QT5: diff --git a/labelme/widgets/color_dialog.py b/labelme/widgets/color_dialog.py index f1590a3e1..a53d8cb27 100644 --- a/labelme/widgets/color_dialog.py +++ b/labelme/widgets/color_dialog.py @@ -3,7 +3,7 @@ class ColorDialog(QtWidgets.QColorDialog): def __init__(self, parent=None): - super(ColorDialog, self).__init__(parent) + super().__init__(parent) self.setOption(QtWidgets.QColorDialog.ShowAlphaChannel) # The Mac native dialog does not support our restore button. self.setOption(QtWidgets.QColorDialog.DontUseNativeDialog) diff --git a/labelme/widgets/escapable_qlist_widget.py b/labelme/widgets/escapable_qlist_widget.py index 546934421..2a033d84e 100644 --- a/labelme/widgets/escapable_qlist_widget.py +++ b/labelme/widgets/escapable_qlist_widget.py @@ -4,6 +4,6 @@ class EscapableQListWidget(QtWidgets.QListWidget): def keyPressEvent(self, event): - super(EscapableQListWidget, self).keyPressEvent(event) + super().keyPressEvent(event) if event.key() == Qt.Key_Escape: self.clearSelection() diff --git a/labelme/widgets/file_dialog_preview.py b/labelme/widgets/file_dialog_preview.py index c5740ef53..f355fdeec 100644 --- a/labelme/widgets/file_dialog_preview.py +++ b/labelme/widgets/file_dialog_preview.py @@ -7,7 +7,7 @@ class ScrollAreaPreview(QtWidgets.QScrollArea): def __init__(self, *args, **kwargs): - super(ScrollAreaPreview, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.setWidgetResizable(True) @@ -33,7 +33,7 @@ def clear(self): class FileDialogPreview(QtWidgets.QFileDialog): def __init__(self, *args, **kwargs): - super(FileDialogPreview, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.setOption(self.DontUseNativeDialog, True) self.labelPreview = ScrollAreaPreview(self) diff --git a/labelme/widgets/label_dialog.py b/labelme/widgets/label_dialog.py index 95b7b6868..14455180a 100644 --- a/labelme/widgets/label_dialog.py +++ b/labelme/widgets/label_dialog.py @@ -23,7 +23,7 @@ def keyPressEvent(self, e): if e.key() in [QtCore.Qt.Key_Up, QtCore.Qt.Key_Down]: self.list_widget.keyPressEvent(e) else: - super(LabelQLineEdit, self).keyPressEvent(e) + super().keyPressEvent(e) class LabelDialog(QtWidgets.QDialog): @@ -42,7 +42,7 @@ def __init__( fit_to_content = {"row": False, "column": True} self._fit_to_content = fit_to_content - super(LabelDialog, self).__init__(parent) + super().__init__(parent) self.edit = LabelQLineEdit() self.edit.setPlaceholderText(text) self.edit.setValidator(labelme.utils.labelValidator()) @@ -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(f"Label list has duplicate '{text}'") + logger.warning("Label list has duplicate %r", text) self.labelList.setCurrentItem(items[0]) row = self.labelList.row(items[0]) self.edit.completer().setCurrentRow(row) diff --git a/labelme/widgets/label_list_widget.py b/labelme/widgets/label_list_widget.py index 96f58979d..275ee6993 100644 --- a/labelme/widgets/label_list_widget.py +++ b/labelme/widgets/label_list_widget.py @@ -9,7 +9,7 @@ # https://stackoverflow.com/a/2039745/4158863 class HTMLDelegate(QtWidgets.QStyledItemDelegate): def __init__(self, parent=None): - super(HTMLDelegate, self).__init__() + super().__init__() self.doc = QtGui.QTextDocument(self) def paint(self, painter, option, index): @@ -67,7 +67,7 @@ def sizeHint(self, option, index): class LabelListWidgetItem(QtGui.QStandardItem): def __init__(self, text=None, shape=None): - super(LabelListWidgetItem, self).__init__() + super().__init__() self.setText(text or "") self.setShape(shape) @@ -106,7 +106,7 @@ class LabelListWidget(QtWidgets.QListView): itemSelectionChanged = QtCore.Signal(list, list) def __init__(self): - super(LabelListWidget, self).__init__() + super().__init__() self._selectedItems = [] self.setWindowFlags(Qt.Window) diff --git a/labelme/widgets/tool_bar.py b/labelme/widgets/tool_bar.py index a0087242c..75a595fba 100644 --- a/labelme/widgets/tool_bar.py +++ b/labelme/widgets/tool_bar.py @@ -4,7 +4,7 @@ class ToolBar(QtWidgets.QToolBar): def __init__(self, title): - super(ToolBar, self).__init__(title) + super().__init__(title) layout = self.layout() m = (0, 0, 0, 0) layout.setSpacing(0) @@ -14,7 +14,7 @@ def __init__(self, title): def addAction(self, action): if isinstance(action, QtWidgets.QWidgetAction): - return super(ToolBar, self).addAction(action) + return super().addAction(action) btn = QtWidgets.QToolButton() btn.setDefaultAction(action) btn.setToolButtonStyle(self.toolButtonStyle()) diff --git a/labelme/widgets/unique_label_qlist_widget.py b/labelme/widgets/unique_label_qlist_widget.py index 604ae9e2f..48ed4c2d3 100644 --- a/labelme/widgets/unique_label_qlist_widget.py +++ b/labelme/widgets/unique_label_qlist_widget.py @@ -9,7 +9,7 @@ class UniqueLabelQListWidget(EscapableQListWidget): def mousePressEvent(self, event): - super(UniqueLabelQListWidget, self).mousePressEvent(event) + super().mousePressEvent(event) if not self.indexAt(event.pos()).isValid(): self.clearSelection() diff --git a/labelme/widgets/zoom_widget.py b/labelme/widgets/zoom_widget.py index 13fb2c253..bd4d8128b 100644 --- a/labelme/widgets/zoom_widget.py +++ b/labelme/widgets/zoom_widget.py @@ -5,7 +5,7 @@ class ZoomWidget(QtWidgets.QSpinBox): def __init__(self, value=100): - super(ZoomWidget, self).__init__() + super().__init__() self.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons) self.setRange(1, 1000) self.setSuffix(" %") @@ -15,7 +15,7 @@ def __init__(self, value=100): self.setAlignment(QtCore.Qt.AlignCenter) def minimumSizeHint(self): - height = super(ZoomWidget, self).minimumSizeHint().height() + height = super().minimumSizeHint().height() fm = QtGui.QFontMetrics(self.font()) width = fm.width(str(self.maximum())) return QtCore.QSize(width, height)