Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop support for out-of-support versions of Python, apply upgrade fixes #1478

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
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
32 changes: 15 additions & 17 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 @@ -88,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.
Expand Down Expand Up @@ -914,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:
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 @@ -1773,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"
Expand Down Expand Up @@ -1821,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():
Expand Down Expand Up @@ -1902,11 +1900,11 @@ 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(
formats + ["*%s" % LabelFile.suffix]
formats + [f"*{LabelFile.suffix}"]
)
fileDialog = FileDialogPreview(self)
fileDialog.setFileMode(FileDialogPreview.ExistingFile)
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("Label file is removed: %s", label_file)

item = self.fileListWidget.currentItem()
item.setCheckState(Qt.Unchecked)
Expand Down Expand Up @@ -2081,7 +2079,7 @@ def mayContinue(self):

def errorMessage(self, title, message):
return QtWidgets.QMessageBox.critical(
self, title, "<p><b>%s</b></p>%s" % (title, message)
self, title, f"<p><b>{title}</b></p>{message}"
)

def currentPath(self):
Expand Down Expand Up @@ -2157,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()
]

Expand Down Expand Up @@ -2216,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()
]

Expand Down
19 changes: 8 additions & 11 deletions labelme/cli/draw_label_png.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,14 @@ 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("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(
[
"{}:{}".format(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
Expand All @@ -75,7 +72,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("Saved to: %s", 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("Saved to: %s", out_dir)


if __name__ == "__main__":
Expand Down
13 changes: 6 additions & 7 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 @@ -35,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")

Expand All @@ -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 All @@ -92,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)
Expand Down
18 changes: 6 additions & 12 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("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)
Expand All @@ -35,24 +35,18 @@ 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("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(
"Unexpected value for config key 'validate_label': {}".format(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(
"Unexpected value for config key 'shape_color': {}".format(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(
"Duplicates are detected for config key 'labels': {}".format(value)
)
raise ValueError(f"Duplicates are detected for config key 'labels': {value}")


def get_config(config_file_or_yaml=None, config_from_args=None):
Expand All @@ -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("Loading config file from: {}".format(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)

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("Failed opening image file: %r", 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
Loading