예제 #1
0
def main():
    ## -- log --
    settings = QtCore.QSettings(osp.join(pjpath, "config/setting.ini"),
                                QtCore.QSettings.IniFormat)
    #
    # logFolder = settings.value("logFolder")
    # logLevel = settings.value("logLevel")
    # logDays = settings.value("logDays")
    #
    # if logFolder is None or len(logFolder) == 0:
    #     logFolder = osp.normcase(osp.join(pjpath, "log"))
    # if not osp.exists(logFolder):
    #     os.makedirs(logFolder)
    #
    # if logLevel:
    #     logLevel = eval(logLevel)
    # else:
    #     logLevel = logging.DEBUG
    # if logDays:
    #     logDays = int(logDays)
    # else:
    #     logDays = 7
    # # TODO: 删除大于logDays 的 log
    #
    # t = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    # logging.basicConfig(
    #     level=logging.DEBUG,
    #     filename=osp.normcase(osp.join(logFolder, f"eiseg-{t}.log")),
    #     format="%(levelname)s - %(asctime)s - %(filename)s - %(funcName)s - %(message)s",
    # )
    # logger = logging.getLogger("EISeg Logger")
    # handler = logging.FileHandler(osp.normcase(osp.join(logFolder, f"eiseg-{t}.log")))
    #
    # handler.setFormatter(
    #     logging.Formatter(
    #         "%(levelname)s - %(asctime)s - %(filename)s - %(funcName)s - %(message)s"
    #     )
    # )
    # logger.addHandler(handler)
    # logger.info("test info")
    #
    app = QApplication(sys.argv)
    lang = settings.value("language")
    if lang != "中文":
        trans = QtCore.QTranslator(app)
        trans.load(osp.join(pjpath, f"util/translate/{lang}"))
        app.installTranslator(trans)

    window = APP_EISeg()  # 创建对象
    window.currLanguage = lang
    window.showMaximized()  # 全屏显示窗口
    # 加载近期模型
    QApplication.processEvents()
    window.loadRecentModelParam()
    sys.exit(app.exec())
예제 #2
0
def main():
    app = QApplication(sys.argv)
    lang = QtCore.QSettings(osp.join(pjpath, "config/setting.ini"),
                            QtCore.QSettings.IniFormat).value("language")
    if lang != "中文":
        trans = QtCore.QTranslator(app)
        trans.load(osp.join(pjpath, f"util/translate/{lang}"))
        app.installTranslator(trans)

    window = APP_EISeg()  # 创建对象
    window.showMaximized()  # 全屏显示窗口
    # 加载近期模型
    QApplication.processEvents()
    window.loadRecentModelParam()
    sys.exit(app.exec_())
예제 #3
0
def _set_locale(app):
    """Set locale and load translation if available.

    Localize the application using the system locale numpy seems to
    have problems with decimal separator in some locales (catalan,
    german...) so C locale is always used for numbers.

    """
    locale.setlocale(locale.LC_ALL, '')
    locale.setlocale(locale.LC_NUMERIC, 'C')

    locale_name = qtcore.QLocale.system().name()
    translator = qtcore.QTranslator()
    if translator.load('vitables_' + locale_name, _I18N_PATH):
        app.installTranslator(translator)
    return translator
예제 #4
0
def main():
    translator = QtCore.QTranslator()
    system_language = QLocale.languageToString(QLocale.system().language())
    print("System Locale: {}".format(system_language))
    print("Localization loaded: {}".format(
        translator.load("{}.qm".format(system_language.lower()),
                        "translations")))
    if translator.isEmpty():
        print("Fallback Localization loaded: {}".format(
            translator.load("english.qm", "translations")))
    app = QtWidgets.QApplication(sys.argv)
    app.installTranslator(translator)

    w = QtWidgets.QWidget()
    trayIcon = SystemTrayIcon(QtGui.QIcon("icons/icon.png"), w)

    trayIcon.show()
    sys.exit(app.exec_())
예제 #5
0
    def __init__(self):
        super(SimpleApp, self).__init__([])

        self.translator = QtCore.QTranslator()
        self.default_font = QtGui.QFont()

        if sys.version_info < (3,) :
            settings_path = ".easygui-qt2"
        else:
            settings_path = ".easygui-qt3"
        self.config_path = os.path.join(os.path.expanduser("~"),
                                         settings_path)
        try:
            self.load_config()
            self.setFont(self.default_font)
        except:
            pass

        self.save_config()
예제 #6
0
	def __init__(self, plugin_file=None):

		"""
		desc:
			Constructor.

		arguments:
			plugin_file:	The location of the plugin script file.
		"""

		if plugin_file is not None:
			# The __file__ variable is generally a str, which will cause unicode
			# errors. Therefore, convert this here if necessary.
			plugin_file = safe_decode(plugin_file,
				enc=misc.filesystem_encoding())
			# These lines makes sure that the icons and help file are recognized
			# by OpenSesame.
			self.plugin_folder = os.path.dirname(plugin_file)
			self.experiment.resources[u'%s.html' % self.item_type] = \
				os.path.join(self.plugin_folder, u'%s.html' \
				% self.item_type)
			self.experiment.resources[u'%s.md' % self.item_type] = \
				os.path.join(self.plugin_folder, u'%s.md' \
				% self.item_type)
			# Install a translation file if there is one. Most plugins have
			# their translations as part of the OpenSesame main translations.
			# However, separate plugins can bring their own translation.
			translation_file = os.path.join(self.plugin_folder, u'resources',
				u'locale', u'%s.qm' % self.main_window._locale)
			if os.path.exists(translation_file):
				translator = QtCore.QTranslator()
				translator.load(translation_file)
				QtCore.QCoreApplication.installTranslator(translator)
			self.init_item_icon()
		else:
			self.qicon = None
		self.lock = False
		qtitem.qtitem.__init__(self)
예제 #7
0
 def set_locale(self, locale, save=True):
     """Sets the language of the basic controls for PyQt
        from a locale - provided that the corresponding qm files
        are present in the PyQt distribution.
     """
     global QM_FILES
     if QM_FILES is None:
         QM_FILES = utils.find_qm_files()
     if locale in QM_FILES:
         if self.translator.load("qt_" + locale, QM_FILES[locale]):
             self.installTranslator(self.translator)
             self.config['locale'] = locale
         else:
             print("language not available")
     elif locale == "default" and self.config['locale'] != 'default':
         self.removeTranslator(self.translator)
         self.translator = QtCore.QTranslator()
         self.config['locale'] = 'default'
     elif self.config['locale'] in QM_FILES:
         if self.translator.load("qt_" + self.config['locale'],
                                      QM_FILES[self.config['locale']]):
             self.installTranslator(self.translator)
     if save:
         self.save_config()
예제 #8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--version',
                        '-V',
                        action='store_true',
                        help='show version')
    parser.add_argument('--reset-config',
                        action='store_true',
                        help='reset qt config')
    parser.add_argument(
        '--logger-level',
        default='info',
        choices=['debug', 'info', 'warning', 'fatal', 'error'],
        help='logger level',
    )
    parser.add_argument('filename', nargs='?', help='image or label filename')
    parser.add_argument(
        '--output',
        '-O',
        '-o',
        help='output file or directory (if it ends with .json it is '
        'recognized as file, else as directory)')
    default_config_file = os.path.join(os.path.expanduser('~'), '.labelmerc')
    parser.add_argument(
        '--config',
        dest='config_file',
        help='config file (default: %s)' % default_config_file,
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        '--nodata',
        dest='store_data',
        action='store_false',
        help='stop storing image data to JSON file',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--autosave',
        dest='auto_save',
        action='store_true',
        help='auto save',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--nosortlabels',
        dest='sort_labels',
        action='store_false',
        help='stop sorting labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--flags',
        help='comma separated list of flags OR file containing flags',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labelflags',
        dest='label_flags',
        help='yaml string of label specific flags OR file containing json '
        'string of label specific flags (ex. {person-\d+: [male, tall], '
        'dog-\d+: [black, brown, white], .*: [occluded]})',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--labels',
        help='comma separated list of labels OR file containing labels',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--validatelabel',
        dest='validate_label',
        choices=['exact', 'instance'],
        help='label validation types',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--keep-prev',
        action='store_true',
        help='keep annotation of previous frame',
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        '--epsilon',
        type=float,
        help='epsilon to find nearest vertex on canvas',
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

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

    logger.setLevel(getattr(logging, args.logger_level.upper()))

    if hasattr(args, 'flags'):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, 'r', encoding='utf-8') as f:
                args.flags = [l.strip() for l in f if l.strip()]
        else:
            args.flags = [l for l in args.flags.split(',') if l]

    if hasattr(args, 'labels'):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, 'r', encoding='utf-8') as f:
                args.labels = [l.strip() for l in f if l.strip()]
        else:
            args.labels = [l for l in args.labels.split(',') if l]

    if hasattr(args, 'label_flags'):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, 'r', encoding='utf-8') as f:
                args.label_flags = yaml.safe_load(f)
        else:
            args.label_flags = yaml.safe_load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop('version')
    reset_config = config_from_args.pop('reset_config')
    filename = config_from_args.pop('filename')
    output = config_from_args.pop('output')
    config_file = config_from_args.pop('config_file')
    config = get_config(config_from_args, config_file)

    if not config['labels'] and config['validate_label']:
        logger.error('--labels must be specified with --validatelabel or '
                     'validate_label: true in the config file '
                     '(ex. ~/.labelmerc).')
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith('.json'):
            output_file = output
        else:
            output_dir = output

    translator = QtCore.QTranslator()
    translator.load(QtCore.QLocale.system().name(),
                    osp.dirname(osp.abspath(__file__)) + '/translate')
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon('icon'))
    app.installTranslator(translator)
    win = MainWindow(
        config=config,
        filename=filename,
        output_file=output_file,
        output_dir=output_dir,
    )

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

    win.show()
    win.raise_()
    sys.exit(app.exec_())
예제 #9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version",
                        "-V",
                        action="store_true",
                        help="show version")
    parser.add_argument("--reset-config",
                        action="store_true",
                        help="reset qt config")
    parser.add_argument(
        "--logger-level",
        default="info",
        choices=["debug", "info", "warning", "fatal", "error"],
        help="logger level",
    )
    parser.add_argument("filename", nargs="?", help="image or label filename")
    parser.add_argument(
        "--output",
        "-O",
        "-o",
        help="output file or directory (if it ends with .json it is "
        "recognized as file, else as directory)",
    )
    default_config_file = os.path.join(os.path.expanduser("~"), ".labelmerc")
    parser.add_argument(
        "--config",
        dest="config",
        help="config file or yaml-format string (default: {})".format(
            default_config_file),
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        "--nodata",
        dest="store_data",
        action="store_false",
        help="stop storing image data to JSON file",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--autosave",
        dest="auto_save",
        action="store_true",
        help="auto save",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--nosortlabels",
        dest="sort_labels",
        action="store_false",
        help="stop sorting labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--flags",
        help="comma separated list of flags OR file containing flags",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labelflags",
        dest="label_flags",
        help=r"yaml string of label specific flags OR file containing json "
        r"string of label specific flags (ex. {person-\d+: [male, tall], "
        r"dog-\d+: [black, brown, white], .*: [occluded]})",  # NOQA
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labels",
        help="comma separated list of labels OR file containing labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--validatelabel",
        dest="validate_label",
        choices=["exact"],
        help="label validation types",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--keep-prev",
        action="store_true",
        help="keep annotation of previous frame",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--epsilon",
        type=float,
        help="epsilon to find nearest vertex on canvas",
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

    if os.name == 'posix':
        st = os.stat('./script.sh')
        os.chmod('./script.sh', st.st_mode | stat.S_IEXEC)

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

    logger.setLevel(getattr(logging, args.logger_level.upper()))

    if hasattr(args, "flags"):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, "r", encoding="utf-8") as f:
                args.flags = [line.strip() for line in f if line.strip()]
        else:
            args.flags = [line for line in args.flags.split(",") if line]

    if hasattr(args, "labels"):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, "r", encoding="utf-8") as f:
                args.labels = [line.strip() for line in f if line.strip()]
        else:
            args.labels = [line for line in args.labels.split(",") if line]

    if hasattr(args, "label_flags"):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, "r", encoding="utf-8") as f:
                args.label_flags = yaml.safe_load(f)
        else:
            args.label_flags = yaml.safe_load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop("version")
    reset_config = config_from_args.pop("reset_config")
    filename = config_from_args.pop("filename")
    output = config_from_args.pop("output")
    config_file_or_yaml = config_from_args.pop("config")
    config = get_config(config_file_or_yaml, config_from_args)

    if not config["labels"] and config["validate_label"]:
        logger.error("--labels must be specified with --validatelabel or "
                     "validate_label: true in the config file "
                     "(ex. ~/.labelmerc).")
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith(".json"):
            output_file = output
        else:
            output_dir = output

    translator = QtCore.QTranslator()
    translator.load(
        QtCore.QLocale.system().name(),
        osp.dirname(osp.abspath(__file__)) + "/translate",
    )
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon("icon"))
    app.installTranslator(translator)
    win = MainWindow(
        config=config,
        filename=filename,
        output_file=output_file,
        output_dir=output_dir,
    )

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

    win.show()
    win.raise_()
    app.exec_()
    win.terminate_subprocess()
    sys.exit(1)
예제 #10
0
    ### Grab existing QApplication
    # Only one QApplication is allowed per process. This allows running inside
    # Qt-based IDEs like Spyder.
    existing = QtWidgets.qApp.instance()
    if existing:
        app = existing
    else:
        app = QtWidgets.QApplication(sys.argv)
    ### Parsing command-line arguments/options
    parser = argparse.ArgumentParser()
    parser.add_argument("--lang",
                        nargs="?",
                        help="Language to run (override system language)")
    try:
        args = parser.parse_args()
    except:
        parser.print_help()
        sys.exit(-1)
    lang = args.lang or QtCore.QLocale.system().name()
    ### Setup internationalization/localization (i18n/l10n)
    translator = QtCore.QTranslator()
    translator.load(frozen(osp.join("data", "main_{}.qm".format(lang))))
    QtWidgets.qApp.installTranslator(translator)
    QtCore.QLocale().setDefault(QtCore.QLocale(lang))
    ### Create main window and run
    wnd = WndMain()
    if existing:
        self = wnd  # Makes it easier to debug with Spyder's F9 inside a class
    else:
        sys.exit(app.exec_())
예제 #11
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version",
                        "-V",
                        action="store_true",
                        help="show version")
    parser.add_argument(\
      "--reset-config", action="store_true", help="reset qt config"
    )
    parser.add_argument(
        "--logger-level",
        default="info",
        choices=["debug", "info", "warning", "fatal", "error"],
        help="logger level",
    )
    parser.add_argument("filename", nargs="?", help="image or label filename")
    parser.add_argument(
        "--output",
        "-O",
        "-o",
        help="output file or directory (if it ends with .json it is "
        "recognized as file, else as directory)",
    )
    default_config_file = os.path.join(os.path.expanduser("~"), ".mindATrc")
    parser.add_argument(
        "--config",
        dest="config",
        help="config file or yaml-format string (default: {})".format(
            default_config_file),
        default=default_config_file,
    )
    # config for the gui
    parser.add_argument(
        "--nodata",
        dest="store_data",
        action="store_false",
        help="stop storing image data to JSON file",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--autosave",
        dest="auto_save",
        action="store_true",
        help="auto save",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--nosortlabels",
        dest="sort_labels",
        action="store_false",
        help="stop sorting labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--flags",
        help="comma separated list of flags OR file containing flags",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labelflags",
        dest="label_flags",
        help=r"yaml string of label specific flags OR file containing json "
        r"string of label specific flags (ex. {person-\d+: [male, tall], "
        r"dog-\d+: [black, brown, white], .*: [occluded]})",  # NOQA
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--labels",
        help="comma separated list of labels OR file containing labels",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--validatelabel",
        dest="validate_label",
        choices=["exact"],
        help="label validation types",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--keep-prev",
        action="store_true",
        help="keep annotation of previous frame",
        default=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--epsilon",
        type=float,
        help="epsilon to find nearest vertex on canvas",
        default=argparse.SUPPRESS,
    )
    args = parser.parse_args()

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

    logger.setLevel(getattr(logging, args.logger_level.upper()))

    if hasattr(args, "flags"):
        if os.path.isfile(args.flags):
            with codecs.open(args.flags, "r", encoding="utf-8") as f:
                args.flags = [line.strip() for line in f if line.strip()]
        else:
            args.flags = [line for line in args.flags.split(",") if line]

    if hasattr(args, "labels"):
        if os.path.isfile(args.labels):
            with codecs.open(args.labels, "r", encoding="utf-8") as f:
                args.labels = [line.strip() for line in f if line.strip()]
        else:
            args.labels = [line for line in args.labels.split(",") if line]

    if hasattr(args, "label_flags"):
        if os.path.isfile(args.label_flags):
            with codecs.open(args.label_flags, "r", encoding="utf-8") as f:
                args.label_flags = yaml.safe_load(f)
        else:
            args.label_flags = yaml.safe_load(args.label_flags)

    config_from_args = args.__dict__
    config_from_args.pop("version")
    reset_config = config_from_args.pop("reset_config")
    filename = config_from_args.pop("filename")
    output = config_from_args.pop("output")
    config_file_or_yaml = config_from_args.pop("config")
    config = get_config(config_file_or_yaml, config_from_args)

    if not config["labels"] and config["validate_label"]:
        logger.error("--labels must be specified with --validatelabel or "
                     "validate_label: true in the config file "
                     "(ex. ~/.mindATrc).")
        sys.exit(1)

    output_file = None
    output_dir = None
    if output is not None:
        if output.endswith(".json"):
            output_file = output
        else:
            output_dir = output

    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon("icon"))

    languages = support_languages
    language_code = QtCore.QLocale.system().name()
    val = languages.pop(language_code)
    old = languages
    languages = {language_code: val}
    languages.update(old)

    returncode = 0
    while language_code in languages.keys():
        translator = QtCore.QTranslator()
        translator.load(
            language_code,
            get_translator_path(),
        )
        app.installTranslator(translator)
        if "theme" in config:
            theme_name = config["theme"]["default"]
            if theme_name:
                app.setStyleSheet(config["theme"][theme_name])

        win = MainWindow(
            support_languages=list(languages.values()),
            config=config,
            filename=filename,
            output_file=output_file,
            output_dir=output_dir,
        )

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

        win.show()
        win.raise_()
        returncode = app.exec_()
        if returncode - MainWindow.RESTART_CODE in range(len(languages)):
            language_code = list(languages.keys())[returncode -
                                                   MainWindow.RESTART_CODE]
            val = languages.pop(language_code)
            old = languages
            languages = {language_code: val}
            languages.update(old)
            win.close()

        elif returncode - MainWindow.RESTART_CODE == MainWindow.RESET_CONFIG:
            os.remove(osp.join(osp.expanduser("~"), ".mindATrc"))
            config = get_default_config(True)
            win.close()

        else:
            language_code = 0
        app.removeTranslator(translator)

    sys.exit(returncode)
    return returncode