From cd287e97387b7f9be6c812864ac081cede99e736 Mon Sep 17 00:00:00 2001 From: Mika Fischer Date: Fri, 24 Jun 2011 10:23:03 +0200 Subject: [PATCH] More changes for Python 3 --- doc/conf.py | 12 ++++++------ sloth/annotations/container.py | 1 - sloth/annotations/model.py | 10 +++++----- sloth/conf/__init__.py | 2 +- sloth/core/cli.py | 2 +- sloth/core/commands.py | 2 +- sloth/core/labeltool.py | 11 ++++++----- sloth/core/utils.py | 2 +- sloth/gui/annotationscene.py | 10 ++++++---- sloth/gui/buttonarea.py | 32 +++++++++++++++++--------------- sloth/items/factory.py | 2 +- sloth/plugins/facedetector.py | 2 -- sloth/utils/importlib.py | 2 +- 13 files changed, 46 insertions(+), 44 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index 624ffed..4e1ae86 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -40,8 +40,8 @@ source_suffix = '.rst' master_doc = 'index' # General information about the project. -project = u'Labeltool' -copyright = u'2011, cv:hci lab, Institute for Anthropomatics, Karlsruhe Institute of Technology' +project = 'Labeltool' +copyright = '2011, cv:hci lab, Institute for Anthropomatics, Karlsruhe Institute of Technology' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -180,8 +180,8 @@ todo_include_todos = True # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'Labeltool.tex', u'Labeltool Documentation', - u'cv:hci lab, Institute for Anthropomatics, Karlsruhe Institute of Technology', 'manual'), + ('index', 'Labeltool.tex', 'Labeltool Documentation', + 'cv:hci lab, Institute for Anthropomatics, Karlsruhe Institute of Technology', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -213,6 +213,6 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'labeltool', u'Labeltool Documentation', - [u'cv:hci lab'], 1) + ('index', 'labeltool', 'Labeltool Documentation', + ['cv:hci lab'], 1) ] diff --git a/sloth/annotations/container.py b/sloth/annotations/container.py index 8757a96..8b71a45 100644 --- a/sloth/annotations/container.py +++ b/sloth/annotations/container.py @@ -221,7 +221,6 @@ class FileNameListContainer(AnnotationContainer): def parseFromFile(self, filename): self.basedir_ = os.path.dirname(filename) f = open(filename, "r") - print "Opening", filename annotations = [] for line in f: diff --git a/sloth/annotations/model.py b/sloth/annotations/model.py index e62d959..e8c547c 100644 --- a/sloth/annotations/model.py +++ b/sloth/annotations/model.py @@ -198,7 +198,7 @@ class KeyValueModelItem(ModelItem, MutableMapping): return len(self._dict) def __iter__(self): - return self._dict.iterkeys() + return iter(self._dict.keys()) def __getitem__(self, key): return self._dict[key] @@ -269,7 +269,7 @@ class ImageModelItem(ModelItem): def updateAnnotation(self, ann): for child in self._children: if child.type() == ann['type']: - if (child.has_key('id') and ann.has_key('id') and child['id'] == ann['id']) or (not child.has_key('id') and not ann.has_key('id')): + if ('id' in child and 'id' in ann and child['id'] == ann['id']) or ('id' not in child and 'id' not in ann): ann[None] = None child.setData(QVariant(ann), DataRole, 1) return @@ -278,7 +278,7 @@ class ImageModelItem(ModelItem): class ImageFileModelItem(FileModelItem, ImageModelItem): def __init__(self, fileinfo): annotations = fileinfo.get("annotations", []) - if fileinfo.has_key("annotations"): + if "annotations" in fileinfo: del fileinfo["annotations"] FileModelItem.__init__(self, fileinfo) ImageModelItem.__init__(self, annotations) @@ -296,7 +296,7 @@ class ImageFileModelItem(FileModelItem, ImageModelItem): class VideoFileModelItem(FileModelItem): def __init__(self, fileinfo): frameinfos = fileinfo.get("frames", []) - if fileinfo.has_key("frames"): + if "frames" in fileinfo: del fileinfo["frames"] FileModelItem.__init__(self, fileinfo) @@ -311,7 +311,7 @@ class VideoFileModelItem(FileModelItem): class FrameModelItem(ImageModelItem, KeyValueModelItem): def __init__(self, frameinfo): annotations = frameinfo.get("annotations", []) - if frameinfo.has_key("annotations"): + if "annotations" in frameinfo: del frameinfo["annotations"] KeyValueModelItem.__init__(self) ImageModelItem.__init__(self, annotations) diff --git a/sloth/conf/__init__.py b/sloth/conf/__init__.py index 66f1501..4ea9d8e 100644 --- a/sloth/conf/__init__.py +++ b/sloth/conf/__init__.py @@ -19,7 +19,7 @@ class Config: module_dir, module_name = os.path.split(module_path) sys.path = [module_dir, ] + sys.path mod = importlib.import_module(module_name) - except ImportError, e: + except ImportError as e: raise ImportError("Could not import configuration '%s' (Is it on sys.path?): %s" % (module_path, e)) finally: sys.path = oldpath diff --git a/sloth/core/cli.py b/sloth/core/cli.py index ab42cde..87f1b57 100644 --- a/sloth/core/cli.py +++ b/sloth/core/cli.py @@ -155,7 +155,7 @@ class BaseCommand(object): output = self.handle(*args, **options) if output: self.stdout.write(output) - except CommandError, e: + except CommandError as e: self.stderr.write('Error: %s\n' % e) sys.exit(1) diff --git a/sloth/core/commands.py b/sloth/core/commands.py index 4cbff91..8851ff5 100644 --- a/sloth/core/commands.py +++ b/sloth/core/commands.py @@ -48,7 +48,7 @@ class CreateConfigCommand(BaseCommand): try: shutil.copy(config_template, target) _make_writeable(target) - except OSError, e: + except OSError as e: sys.stderr.write("Notice: Couldn't set permission bits on %s.\n" % target) diff --git a/sloth/core/labeltool.py b/sloth/core/labeltool.py index 66af930..78c13ae 100755 --- a/sloth/core/labeltool.py +++ b/sloth/core/labeltool.py @@ -15,6 +15,8 @@ from sloth.core.cli import LaxOptionParser, BaseCommand from sloth.core.utils import import_callable from sloth import VERSION from sloth.core.commands import get_commands +import logging +LOG = logging.getLogger(__name__) import okapy.videoio as okv @@ -74,7 +76,7 @@ class LabelTool(QObject): """ usage = self.help_text % self.prog_name usage += 'Available subcommands:\n' - commands = get_commands().keys() + commands = list(get_commands().keys()) commands.sort() for cmd in commands: usage += ' %s\n' % cmd @@ -148,9 +150,8 @@ class LabelTool(QObject): if len(args) > 1: try: self.loadAnnotations(args[1], handleErrors=False) - except Exception, e: - print "Error loading annotations:", e - raise + except Exception as e: + LOG.fatal("Error loading annotations: %s" % e) sys.exit(1) else: self.clearAnnotations() @@ -215,7 +216,7 @@ class LabelTool(QObject): self._model = AnnotationModel(self.container_.load(fname)) msg = "Successfully loaded %s (%d files, %d annotations)" % \ (fname, self._model.root().numFiles(), self._model.root().numAnnotations()) - except Exception, e: + except Exception as e: if handleErrors: msg = "Error: Loading failed (%s)" % str(e) else: diff --git a/sloth/core/utils.py b/sloth/core/utils.py index 1facf3f..dd76ed9 100644 --- a/sloth/core/utils.py +++ b/sloth/core/utils.py @@ -11,7 +11,7 @@ def import_callable(module_path_name): raise exceptions.ImproperlyConfigured('%s is not a valid module path' % module_path_name) try: mod = importlib.import_module(module_path) - except ImportError, e: + except ImportError as e: raise exceptions.ImproperlyConfigured('Error importing module %s: "%s"' % (module_path, e)) try: item_callable = getattr(mod, name) diff --git a/sloth/gui/annotationscene.py b/sloth/gui/annotationscene.py index f0800c9..8759e3d 100644 --- a/sloth/gui/annotationscene.py +++ b/sloth/gui/annotationscene.py @@ -5,6 +5,8 @@ from sloth.items import * from sloth.annotations.model import TypeRole from sloth.core.exceptions import InvalidArgumentException import okapy +import logging +LOG = logging.getLogger(__name__) class AnnotationScene(QGraphicsScene): """Dies ist ein Test""" @@ -114,7 +116,7 @@ class AnnotationScene(QGraphicsScene): self.inserter_ = None def setMode(self, mode): - print "setMode :", mode + LOG.debug("setMode : %s" % mode) # Abort current inserter if self.inserter_ is not None: @@ -145,7 +147,7 @@ class AnnotationScene(QGraphicsScene): #______________________________________________________________________________________________________ def mousePressEvent(self, event): if self.debug_: - print "mousePressEvent", self.sceneRect().contains(event.scenePos()), event.scenePos() + LOG.debug("mousePressEvent %s %s" % (self.sceneRect().contains(event.scenePos()), event.scenePos())) if self.inserter_ is not None: if not self.sceneRect().contains(event.scenePos()) and \ not self.inserter_.allowOutOfSceneEvents(): @@ -159,7 +161,7 @@ class AnnotationScene(QGraphicsScene): def mouseReleaseEvent(self, event): if self.debug_: - print "mouseReleaseEvent", self.sceneRect().contains(event.scenePos()), event.scenePos() + LOG.debug("mouseReleaseEvent %s %s" % (self.sceneRect().contains(event.scenePos()), event.scenePos())) if self.inserter_ is not None: # insert mode self.inserter_.mouseReleaseEvent(event, self.image_item_) @@ -228,7 +230,7 @@ class AnnotationScene(QGraphicsScene): def keyPressEvent(self, event): if self.debug_: - print "keyPressEvent", event + LOG.debug("keyPressEvent %s" % event) if self.model_ is None or not self.root_.isValid(): event.ignore() diff --git a/sloth/gui/buttonarea.py b/sloth/gui/buttonarea.py index 9f5a717..2dd8181 100644 --- a/sloth/gui/buttonarea.py +++ b/sloth/gui/buttonarea.py @@ -1,7 +1,9 @@ -import sys, os +import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from sloth.gui.floatinglayout import FloatingLayout +import logging +LOG = logging.getLogger(__name__) def unique_list(seq): seen = {} @@ -102,14 +104,14 @@ class ButtonArea(QWidget): self.setLayout(self.vlayout) def stateHasChanged(self, state): - print "stateChanged(object)", state + LOG.debug("stateChanged(object) %s", state) def init_button_lists(self): for label_name in self.label_names: button = self.label_button_list.add_button(label_name) self.label_button_list.selectionChanged.connect(self.clickedLabelButton) - for key, property_values in self.properties.iteritems(): + for key, property_values in self.properties.items(): if key in ["type", "class"]: continue button_list = ButtonListWidget(key) @@ -119,7 +121,7 @@ class ButtonArea(QWidget): button_list.selectionChanged.connect(self.clickedButton) button_list.hide() - print key + LOG.debug(key) self.property_button_lists[key] = button_list self.vlayout.addWidget(button_list) @@ -133,8 +135,8 @@ class ButtonArea(QWidget): button.setToolTip("[" + str(hotkey) + "]") def show_only_label_properties(self, label_name): - for name, button_list in self.property_button_lists.iteritems(): - if self.label_properties.has_key(label_name) and name in self.label_properties[label_name].keys(): + for name, button_list in self.property_button_lists.items(): + if label_name in self.label_properties and name in self.label_properties[label_name].keys(): button_list.show() else: button_list.hide() @@ -142,8 +144,8 @@ class ButtonArea(QWidget): def add_label(self, label_name, properties = {}): self.label_names.append(label_name) self.label_properties[label_name] = properties - for key, value in properties.iteritems(): - if self.properties.has_key(key): + for key, value in properties.items(): + if key in self.properties: self.properties[key] = unique_list(self.properties[key] + value) else: @@ -160,12 +162,12 @@ class ButtonArea(QWidget): if label_button != None: result = {} label = str(label_button.text()) - if self.label_properties.has_key(label): - if self.label_properties[label].has_key("type"): + if label in self.label_properties: + if "type" in self.label_properties[label]: result["type"] = self.label_properties[label]["type"] - if self.label_properties[label].has_key("class"): + if "class" in self.label_properties[label]: result["class"] = self.label_properties[label]["class"] - for name, button_list in self.property_button_lists.iteritems(): + for name, button_list in self.property_button_lists.items(): if button_list.isVisible(): checked_button = button_list.get_checked_button() if checked_button != None: @@ -175,17 +177,17 @@ class ButtonArea(QWidget): return None def clickedButton(self, newselection): - print "selectionChanged:", newselection + LOG.debug("selectionChanged: %s" % newselection) self.stateChanged.emit(self.get_current_state()) def clickedLabelButton(self, label_name): #button = self.get_checked_label_button() #print button if label_name != None: - print "ButtonArea:", label_name + LOG.debug("ButtonArea: %s" % label_name) self.show_only_label_properties(label_name) else: - print "Selection Mode" + LOG.debug("Selection Mode") self.show_only_label_properties("") self.stateChanged.emit(self.get_current_state()) diff --git a/sloth/items/factory.py b/sloth/items/factory.py index 7abb135..4c5f530 100644 --- a/sloth/items/factory.py +++ b/sloth/items/factory.py @@ -19,7 +19,7 @@ class Factory: self.items_ = {} if items is not None: - for _type, item in items.iteritems(): + for _type, item in items.items(): self.register(_type, item, replace=True) def register(self, _type, item, replace=False): diff --git a/sloth/plugins/facedetector.py b/sloth/plugins/facedetector.py index f1a0f9b..34647d9 100644 --- a/sloth/plugins/facedetector.py +++ b/sloth/plugins/facedetector.py @@ -57,7 +57,6 @@ class FaceDetectorPlugin(QObject): self.sc_.setEnabled(True) def doit(self): - print "Loading detector..." det = BinaryPatternFaceDetector("/cvhci/data/mctcascades/new-detectors/face_frontal_new.xml") self.sc_.setEnabled(False) model = self.wnd_.model_ @@ -70,7 +69,6 @@ class FaceDetectorPlugin(QObject): self.thread.finished.connect(self.on_finished) self.thread.valueChanged.connect(self.on_valueChanged) self.thread.start() - print "Exiting doit()" def action(self): return self.sc_ diff --git a/sloth/utils/importlib.py b/sloth/utils/importlib.py index bb6f8f2..c6ea879 100644 --- a/sloth/utils/importlib.py +++ b/sloth/utils/importlib.py @@ -8,7 +8,7 @@ def _resolve_name(name, package, level): if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) - for x in xrange(level, 1, -1): + for x in range(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: