comictagger/comictaggerlib/main.py

167 lines
6.6 KiB
Python
Raw Normal View History

"""A python app to (automatically) tag comic archives"""
2022-06-02 18:32:16 -07:00
#
# Copyright 2012-2014 Anthony Beville
2022-06-02 18:32:16 -07:00
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
2022-06-02 18:32:16 -07:00
#
# http://www.apache.org/licenses/LICENSE-2.0
2022-06-02 18:32:16 -07:00
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2022-06-02 18:32:16 -07:00
from __future__ import annotations
2022-12-06 00:20:01 -08:00
import argparse
import json
2022-04-04 18:59:26 -07:00
import logging.handlers
Code cleanup Remove no longer used google scripts Remove convenience files from comicataggerlib and import comicapi directly Add type-hints to facilitate auto-complete tools Make PyQt5 code more compatible with PyQt6 Implement automatic tooling isort and black for code formatting Line length has been set to 120 flake8 for code standards with exceptions: E203 - Whitespace before ':' - format compatiblity with black E501 - Line too long - flake8 line limit cannot be set E722 - Do not use bare except - fixing bare except statements is a lot of overhead and there are already many in the codebase These changes, along with some manual fixes creates much more readable code. See examples below: diff --git a/comicapi/comet.py b/comicapi/comet.py index d1741c5..52dc195 100644 --- a/comicapi/comet.py +++ b/comicapi/comet.py @@ -166,7 +166,2 @@ class CoMet: - if credit['role'].lower() in set(self.editor_synonyms): - ET.SubElement( - root, - 'editor').text = "{0}".format( - credit['person']) @@ -174,2 +169,4 @@ class CoMet: self.indent(root) + if credit["role"].lower() in set(self.editor_synonyms): + ET.SubElement(root, "editor").text = str(credit["person"]) diff --git a/comictaggerlib/autotagmatchwindow.py b/comictaggerlib/autotagmatchwindow.py index 4338176..9219f01 100644 --- a/comictaggerlib/autotagmatchwindow.py +++ b/comictaggerlib/autotagmatchwindow.py @@ -63,4 +63,3 @@ class AutoTagMatchWindow(QtWidgets.QDialog): self.skipButton, QtWidgets.QDialogButtonBox.ActionRole) - self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText( - "Accept and Write Tags") + self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Ok).setText("Accept and Write Tags") diff --git a/comictaggerlib/cli.py b/comictaggerlib/cli.py index 688907d..dbd0c2e 100644 --- a/comictaggerlib/cli.py +++ b/comictaggerlib/cli.py @@ -293,7 +293,3 @@ def process_file_cli(filename, opts, settings, match_results): if opts.raw: - print(( - "{0}".format( - str( - ca.readRawCIX(), - errors='ignore')))) + print(ca.read_raw_cix()) else:
2022-04-01 16:50:46 -07:00
import platform
2022-12-06 00:20:01 -08:00
import pprint
import signal
Code cleanup Remove no longer used google scripts Remove convenience files from comicataggerlib and import comicapi directly Add type-hints to facilitate auto-complete tools Make PyQt5 code more compatible with PyQt6 Implement automatic tooling isort and black for code formatting Line length has been set to 120 flake8 for code standards with exceptions: E203 - Whitespace before ':' - format compatiblity with black E501 - Line too long - flake8 line limit cannot be set E722 - Do not use bare except - fixing bare except statements is a lot of overhead and there are already many in the codebase These changes, along with some manual fixes creates much more readable code. See examples below: diff --git a/comicapi/comet.py b/comicapi/comet.py index d1741c5..52dc195 100644 --- a/comicapi/comet.py +++ b/comicapi/comet.py @@ -166,7 +166,2 @@ class CoMet: - if credit['role'].lower() in set(self.editor_synonyms): - ET.SubElement( - root, - 'editor').text = "{0}".format( - credit['person']) @@ -174,2 +169,4 @@ class CoMet: self.indent(root) + if credit["role"].lower() in set(self.editor_synonyms): + ET.SubElement(root, "editor").text = str(credit["person"]) diff --git a/comictaggerlib/autotagmatchwindow.py b/comictaggerlib/autotagmatchwindow.py index 4338176..9219f01 100644 --- a/comictaggerlib/autotagmatchwindow.py +++ b/comictaggerlib/autotagmatchwindow.py @@ -63,4 +63,3 @@ class AutoTagMatchWindow(QtWidgets.QDialog): self.skipButton, QtWidgets.QDialogButtonBox.ActionRole) - self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText( - "Accept and Write Tags") + self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Ok).setText("Accept and Write Tags") diff --git a/comictaggerlib/cli.py b/comictaggerlib/cli.py index 688907d..dbd0c2e 100644 --- a/comictaggerlib/cli.py +++ b/comictaggerlib/cli.py @@ -293,7 +293,3 @@ def process_file_cli(filename, opts, settings, match_results): if opts.raw: - print(( - "{0}".format( - str( - ca.readRawCIX(), - errors='ignore')))) + print(ca.read_raw_cix()) else:
2022-04-01 16:50:46 -07:00
import sys
2022-12-06 00:20:01 -08:00
from typing import Any
import comictalker.comictalkerapi as ct_api
from comicapi import utils
2022-12-06 00:20:01 -08:00
from comictaggerlib import cli, settings
2022-04-04 18:59:26 -07:00
from comictaggerlib.ctversion import version
2022-12-06 00:20:01 -08:00
from comictaggerlib.log import setup_logging
from comictalker.talkerbase import TalkerError
if sys.version_info < (3, 10):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
try:
2022-12-06 00:20:01 -08:00
from comictaggerlib import gui
2022-12-06 00:20:01 -08:00
qt_available = gui.qt_available
except Exception:
qt_available = False
2022-12-06 00:20:01 -08:00
logger = logging.getLogger("comictagger")
2022-04-04 18:59:26 -07:00
2022-12-06 00:20:01 -08:00
logger.setLevel(logging.DEBUG)
2022-04-04 18:59:26 -07:00
2022-12-06 00:20:01 -08:00
def update_publishers(options: dict[str, dict[str, Any]]) -> None:
json_file = options["runtime"]["config"].user_config_dir / "publishers.json"
if json_file.exists():
try:
utils.update_publishers(json.loads(json_file.read_text("utf-8")))
2022-12-06 00:20:01 -08:00
except Exception:
logger.exception("Failed to load publishers from %s", json_file)
2022-12-06 00:20:01 -08:00
# show_exception_box(str(e))
class App:
"""docstring for App"""
def __init__(self) -> None:
self.options: dict[str, dict[str, Any]] = {}
self.initial_arg_parser = settings.initial_cmd_line_parser()
def run(self) -> None:
opts = self.initialize()
self.register_options()
self.parse_options(opts.config)
self.initialize_dirs()
self.ctmain()
def initialize(self) -> argparse.Namespace:
opts, _ = self.initial_arg_parser.parse_known_args()
assert opts is not None
2022-11-23 22:14:09 -08:00
setup_logging(opts.verbose, opts.config.user_log_dir)
2022-12-06 00:20:01 -08:00
return opts
def register_options(self) -> None:
self.manager = settings.Manager(
"""A utility for reading and writing metadata to comic archives.\n\n\nIf no options are given, %(prog)s will run in windowed mode.""",
"For more help visit the wiki at: https://github.com/comictagger/comictagger/wiki",
)
2022-12-06 00:20:01 -08:00
settings.register_commandline(self.manager)
settings.register_settings(self.manager)
def parse_options(self, config_paths: settings.ComicTaggerPaths) -> None:
options = self.manager.parse_options(config_paths.user_config_dir / "settings.json")
2022-12-06 00:20:01 -08:00
self.options = settings.validate_commandline_options(options, self.manager)
self.options = settings.validate_settings(options, self.manager)
def initialize_dirs(self) -> None:
self.options["runtime"]["config"].user_data_dir.mkdir(parents=True, exist_ok=True)
self.options["runtime"]["config"].user_config_dir.mkdir(parents=True, exist_ok=True)
self.options["runtime"]["config"].user_cache_dir.mkdir(parents=True, exist_ok=True)
self.options["runtime"]["config"].user_state_dir.mkdir(parents=True, exist_ok=True)
self.options["runtime"]["config"].user_log_dir.mkdir(parents=True, exist_ok=True)
logger.debug("user_data_dir: %s", self.options["runtime"]["config"].user_data_dir)
logger.debug("user_config_dir: %s", self.options["runtime"]["config"].user_config_dir)
logger.debug("user_cache_dir: %s", self.options["runtime"]["config"].user_cache_dir)
logger.debug("user_state_dir: %s", self.options["runtime"]["config"].user_state_dir)
logger.debug("user_log_dir: %s", self.options["runtime"]["config"].user_log_dir)
def ctmain(self) -> None:
assert self.options is not None
# options already loaded
# manage the CV API key
# None comparison is used so that the empty string can unset the value
if self.options["comicvine"]["cv_api_key"] is not None or self.options["comicvine"]["cv_url"] is not None:
self.manager.save_file(self.options, self.options["runtime"]["config"].user_config_dir / "settings.json")
logger.debug(pprint.pformat(self.options))
if self.options["commands"]["only_set_cv_key"]:
print("Key set") # noqa: T201
return
signal.signal(signal.SIGINT, signal.SIG_DFL)
logger.info(
"ComicTagger Version: %s running on: %s PyInstaller: %s",
version,
platform.system(),
"Yes" if getattr(sys, "frozen", None) else "No",
2022-11-24 10:39:03 -08:00
)
2022-12-06 00:20:01 -08:00
logger.debug("Installed Packages")
for pkg in sorted(importlib_metadata.distributions(), key=lambda x: x.name):
logger.debug("%s\t%s", pkg.metadata["Name"], pkg.metadata["Version"])
2022-04-04 18:59:26 -07:00
2022-12-06 00:20:01 -08:00
utils.load_publishers()
update_publishers(self.options)
2022-12-06 00:20:01 -08:00
if not qt_available and not self.options["runtime"]["no_gui"]:
self.options["runtime"]["no_gui"] = True
logger.warning("PyQt5 is not available. ComicTagger is limited to command-line mode.")
2022-12-06 00:20:01 -08:00
gui_exception = None
2022-04-04 18:59:26 -07:00
try:
2022-12-06 00:20:01 -08:00
talker_api = ct_api.get_comic_talker("comicvine")( # type: ignore[call-arg]
version=version,
cache_folder=self.options["runtime"]["config"].user_cache_dir,
series_match_thresh=self.options["comicvine"]["series_match_search_thresh"],
remove_html_tables=self.options["comicvine"]["remove_html_tables"],
use_series_start_as_volume=self.options["comicvine"]["use_series_start_as_volume"],
2022-11-26 16:47:40 -08:00
wait_on_ratelimit=self.options["autotag"]["wait_and_retry_on_rate_limit"],
2022-12-06 00:20:01 -08:00
api_url=self.options["comicvine"]["cv_url"],
api_key=self.options["comicvine"]["cv_api_key"],
Code cleanup Remove no longer used google scripts Remove convenience files from comicataggerlib and import comicapi directly Add type-hints to facilitate auto-complete tools Make PyQt5 code more compatible with PyQt6 Implement automatic tooling isort and black for code formatting Line length has been set to 120 flake8 for code standards with exceptions: E203 - Whitespace before ':' - format compatiblity with black E501 - Line too long - flake8 line limit cannot be set E722 - Do not use bare except - fixing bare except statements is a lot of overhead and there are already many in the codebase These changes, along with some manual fixes creates much more readable code. See examples below: diff --git a/comicapi/comet.py b/comicapi/comet.py index d1741c5..52dc195 100644 --- a/comicapi/comet.py +++ b/comicapi/comet.py @@ -166,7 +166,2 @@ class CoMet: - if credit['role'].lower() in set(self.editor_synonyms): - ET.SubElement( - root, - 'editor').text = "{0}".format( - credit['person']) @@ -174,2 +169,4 @@ class CoMet: self.indent(root) + if credit["role"].lower() in set(self.editor_synonyms): + ET.SubElement(root, "editor").text = str(credit["person"]) diff --git a/comictaggerlib/autotagmatchwindow.py b/comictaggerlib/autotagmatchwindow.py index 4338176..9219f01 100644 --- a/comictaggerlib/autotagmatchwindow.py +++ b/comictaggerlib/autotagmatchwindow.py @@ -63,4 +63,3 @@ class AutoTagMatchWindow(QtWidgets.QDialog): self.skipButton, QtWidgets.QDialogButtonBox.ActionRole) - self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText( - "Accept and Write Tags") + self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Ok).setText("Accept and Write Tags") diff --git a/comictaggerlib/cli.py b/comictaggerlib/cli.py index 688907d..dbd0c2e 100644 --- a/comictaggerlib/cli.py +++ b/comictaggerlib/cli.py @@ -293,7 +293,3 @@ def process_file_cli(filename, opts, settings, match_results): if opts.raw: - print(( - "{0}".format( - str( - ca.readRawCIX(), - errors='ignore')))) + print(ca.read_raw_cix()) else:
2022-04-01 16:50:46 -07:00
)
2022-12-06 00:20:01 -08:00
except TalkerError as e:
logger.exception("Unable to load talker")
gui_exception = e
if self.options["runtime"]["no_gui"]:
raise SystemExit(1)
if self.options["runtime"]["no_gui"]:
try:
2022-11-26 16:47:18 -08:00
cli.CLI(self.options, talker_api).run()
2022-12-06 00:20:01 -08:00
except Exception:
logger.exception("CLI mode failed")
else:
gui.open_tagger_window(talker_api, self.options, gui_exception)