-
Notifications
You must be signed in to change notification settings - Fork 0
Sourcery refactored master branch #1
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
base: master
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sourcery timed out performing refactorings.
Due to GitHub API limits, only the first 60 comments can be shown.
| so certain steps can be skipped/output limited """ | ||
| self.conda_required_packages = [("tk", )] | ||
| self.output = logger if logger else Output() | ||
| self.output = logger or Output() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Environment.__init__ refactored with the following changes:
- Simplify if expression by using or (
or-if-exp-identity) - Replace list() with [] [×3] (
list-literal)
| retval = (hasattr(sys, "real_prefix") or | ||
| (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix)) | ||
| else: | ||
| prefix = os.path.dirname(sys.prefix) | ||
| retval = (os.path.basename(prefix) == "envs") | ||
| return retval | ||
| return hasattr(sys, "real_prefix") or ( | ||
| hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix | ||
| ) | ||
|
|
||
| prefix = os.path.dirname(sys.prefix) | ||
| return (os.path.basename(prefix) == "envs") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Environment.is_virtualenv refactored with the following changes:
- Lift return into if (
lift-return-into-if) - Swap if/else branches [×2] (
swap-if-else-branches) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
| args = [arg for arg in sys.argv] # pylint:disable=unnecessary-comprehension | ||
| args = list(sys.argv) | ||
| if self.updater: | ||
| from lib.utils import get_backend # pylint:disable=import-outside-toplevel | ||
| args.append("--{}".format(get_backend())) | ||
| args.append(f"--{get_backend()}") | ||
|
|
||
| for arg in args: | ||
| if arg == "--installer": | ||
| self.is_installer = True | ||
| if arg == "--nvidia": | ||
| self.enable_cuda = True | ||
| if arg == "--amd": | ||
| self.enable_amd = True | ||
| elif arg == "--installer": | ||
| self.is_installer = True | ||
| elif arg == "--nvidia": | ||
| self.enable_cuda = True |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Environment.process_arguments refactored with the following changes:
- Replace identity comprehension with call to collection constructor (
identity-comprehension) - Replace call to format with f-string (
use-fstring-for-formatting) - Simplify conditional into switch-like form [×3] (
switch)
This removes the following comments ( why? ):
# pylint:disable=unnecessary-comprehension
| requirements = list() | ||
| git_requirements = list() | ||
| requirements = [] | ||
| git_requirements = [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Environment.get_required_packages refactored with the following changes:
- Replace list() with [] [×2] (
list-literal)
| self.output.info("Setup in %s %s" % (self.os_version[0], self.os_version[1])) | ||
| if not self.updater and not self.os_version[0] in ["Windows", "Linux", "Darwin"]: | ||
| self.output.error("Your system %s is not supported!" % self.os_version[0]) | ||
| self.output.info(f"Setup in {self.os_version[0]} {self.os_version[1]}") | ||
| if not self.updater and self.os_version[0] not in [ | ||
| "Windows", | ||
| "Linux", | ||
| "Darwin", | ||
| ]: | ||
| self.output.error(f"Your system {self.os_version[0]} is not supported!") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Environment.check_system refactored with the following changes:
- Replace interpolated string formatting with f-string [×2] (
replace-interpolation-with-fstring) - Simplify logical expression using De Morgan identities (
de-morgan)
| trm = "{}ERROR {} ".format(self.red, self.default_color) | ||
| trm = f"{self.red}ERROR {self.default_color} " |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Output.error refactored with the following changes:
- Replace call to format with f-string (
use-fstring-for-formatting)
|
|
||
| # Checks not required for installer | ||
| if self.env.is_installer: | ||
| return | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Checks.__init__ refactored with the following changes:
- Lift repeated conditional into its own if statement (
lift-duplicated-conditional) - Use f-string instead of string concatenation (
use-fstring-for-concatenation) - Remove redundant conditional (
remove-redundant-if)
| path = os.popen(f"{locate} nvcc").read() | ||
| if path: | ||
| if path := os.popen(f"{locate} nvcc").read(): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function CudaCheck._cuda_check refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression)
| cudnn_checkfiles = [os.path.join(cudnn_path, header) for header in header_files] | ||
| return cudnn_checkfiles | ||
| return [os.path.join(cudnn_path, header) for header in header_files] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function CudaCheck._get_checkfiles_linux refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| cudnn_checkfiles = [os.path.join(scandir, header) for header in self._cudnn_header_files] | ||
| return cudnn_checkfiles | ||
| return [os.path.join(scandir, header) for header in self._cudnn_header_files] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function CudaCheck._get_checkfiles_windows refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| if len(pkg[0].split("==")) > 1: | ||
| if pkg[0].split("==")[1] != self.env.installed_conda_packages.get(key): | ||
| self.env.conda_missing_packages.append(pkg) | ||
| continue | ||
| if len(pkg[0].split("==")) > 1 and pkg[0].split("==")[ | ||
| 1 | ||
| ] != self.env.installed_conda_packages.get(key): | ||
| self.env.conda_missing_packages.append(pkg) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Install.check_conda_missing_dep refactored with the following changes:
- Merge nested if conditions (
merge-nested-ifs) - Remove redundant continue statement (
remove-redundant-continue)
| pkg = pkg[0] | ||
| if version: | ||
| pkg = "{}{}".format(pkg, ",".join("".join(spec) for spec in version)) | ||
| pkg = f'{pkg}{",".join(("".join(spec) for spec in version))}' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Install.install_python_packages refactored with the following changes:
- Replace call to format with f-string (
use-fstring-for-formatting)
| specs = Requirement.parse(package).specs | ||
| for key, val in TENSORFLOW_REQUIREMENTS.items(): | ||
| req_specs = Requirement.parse("foobar" + key).specs | ||
| req_specs = Requirement.parse(f"foobar{key}").specs |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Install.conda_installer refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation)
| pipexe = [sys.executable, "-m", "pip"] | ||
| # hide info/warning and fix cache hang | ||
| pipexe.extend(["install", "--no-cache-dir"]) | ||
| pipexe = [sys.executable, "-m", "pip", "install", "--no-cache-dir"] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function Install.pip_installer refactored with the following changes:
- Merge extend into list declaration (
merge-list-extend)
This removes the following comments ( why? ):
# hide info/warning and fix cache hang
| mod = ".".join(("tools", tool_name, "cli")) | ||
| module = import_module(mod) | ||
| cliarg_class = getattr(module, "{}Args".format(tool_name.title())) | ||
| cliarg_class = getattr(module, f"{tool_name.title()}Args") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function _get_cli_opts refactored with the following changes:
- Replace call to format with f-string (
use-fstring-for-formatting)
| choices = list() if not choices else choices | ||
| choices = choices or list() | ||
|
|
||
| if None in (section, title, default, info): | ||
| raise ValueError("Default config items must have a section, title, defult and " | ||
| "information text") | ||
| if not self.defaults.get(section, None): | ||
| raise ValueError("Section does not exist: {}".format(section)) | ||
| raise ValueError(f"Section does not exist: {section}") | ||
| if datatype not in (str, bool, float, int, list): | ||
| raise ValueError("'datatype' must be one of str, bool, float or " | ||
| "int: {} - {}".format(section, title)) | ||
| raise ValueError( | ||
| f"'datatype' must be one of str, bool, float or int: {section} - {title}" | ||
| ) | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceswapConfig.add_item refactored with the following changes:
- Simplify if expression by using or (
or-if-exp-identity) - Swap if/else branches of if expression to remove negation (
swap-if-expression) - Replace call to format with f-string [×2] (
use-fstring-for-formatting)
| helptext += "\nChoose from: {}".format(choices) | ||
| helptext += f"\nChoose from: {choices}" | ||
| elif datatype == bool: | ||
| helptext += "\nChoose from: True, False" | ||
| elif datatype == int: | ||
| cmin, cmax = min_max | ||
| helptext += "\nSelect an integer between {} and {}".format(cmin, cmax) | ||
| helptext += f"\nSelect an integer between {cmin} and {cmax}" | ||
| elif datatype == float: | ||
| cmin, cmax = min_max | ||
| helptext += "\nSelect a decimal number between {} and {}".format(cmin, cmax) | ||
| helptext += "\n[Default: {}]".format(default) | ||
| helptext += f"\nSelect a decimal number between {cmin} and {cmax}" | ||
| helptext += f"\n[Default: {default}]" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceswapConfig.expand_helptext refactored with the following changes:
- Replace call to format with f-string [×4] (
use-fstring-for-formatting)
| if is_section: | ||
| helptext = helptext.upper() | ||
| else: | ||
| helptext = "\n{}".format(helptext) | ||
| helptext = helptext.upper() if is_section else f"\n{helptext}" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceswapConfig.format_help refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp) - Replace call to format with f-string (
use-fstring-for-formatting)
| if not all(val in opt["choices"] for val in opt_value): | ||
| if any(val not in opt["choices"] for val in opt_value): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceswapConfig.check_config_choices refactored with the following changes:
- Invert any/all to simplify comparisons (
invert-any-all)
| config_file = os.path.join(configs_path, "{}.ini".format(section)) | ||
| config_file = os.path.join(configs_path, f"{section}.ini") | ||
| if not os.path.exists(config_file): | ||
| mod = import_module("plugins.{}.{}".format(section, "_config")) | ||
| mod = import_module(f"plugins.{section}._config") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function generate_configs refactored with the following changes:
- Replace call to format with f-string [×2] (
use-fstring-for-formatting) - Simplify unnecessary nesting, casting and constant values in f-strings (
simplify-fstring-formatting)
| retval = dict() | ||
| for fpath in reference_file_paths: | ||
| retval[fpath] = {"image": read_image(fpath, raise_error=True), | ||
| "type": "filter"} | ||
| retval = { | ||
| fpath: {"image": read_image(fpath, raise_error=True), "type": "filter"} | ||
| for fpath in reference_file_paths | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceFilter.load_images refactored with the following changes:
- Replace dict() with {} (
dict-literal) - Convert for loop into dictionary comprehension (
dict-comprehension)
| msg = "Rejecting filter face: {} > {}".format(round(avgs["filter"], 2), self.threshold) | ||
| msg = f'Rejecting filter face: {round(avgs["filter"], 2)} > {self.threshold}' | ||
| retval = False | ||
| # nFilter no Filter | ||
| elif not distances["filter"] and avgs["nfilter"] < self.threshold: | ||
| msg = "Rejecting nFilter face: {} < {}".format(round(avgs["nfilter"], 2), | ||
| self.threshold) | ||
| msg = f'Rejecting nFilter face: {round(avgs["nfilter"], 2)} < {self.threshold}' | ||
| retval = False | ||
| # Filter with nFilter | ||
| elif distances["filter"] and distances["nfilter"] and mins["filter"] > mins["nfilter"]: | ||
| msg = ("Rejecting face as distance from nfilter sample is smaller: (filter: {}, " | ||
| "nfilter: {})".format(round(mins["filter"], 2), round(mins["nfilter"], 2))) | ||
| msg = f'Rejecting face as distance from nfilter sample is smaller: (filter: {round(mins["filter"], 2)}, nfilter: {round(mins["nfilter"], 2)})' | ||
|
|
||
| retval = False | ||
| elif distances["filter"] and distances["nfilter"] and avgs["filter"] > avgs["nfilter"]: | ||
| msg = ("Rejecting face as average distance from nfilter sample is smaller: (filter: " | ||
| "{}, nfilter: {})".format(round(mins["filter"], 2), round(mins["nfilter"], 2))) | ||
| msg = f'Rejecting face as average distance from nfilter sample is smaller: (filter: {round(mins["filter"], 2)}, nfilter: {round(mins["nfilter"], 2)})' | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function FaceFilter.check refactored with the following changes:
- Replace call to format with f-string [×5] (
use-fstring-for-formatting)
This removes the following comments ( why? ):
# Filter with nFilter
# nFilter no Filter
| self._log("debug", "Initializing {}".format(self.__class__.__name__)) | ||
| self._log("debug", f"Initializing {self.__class__.__name__}") | ||
|
|
||
| self._plaid = None | ||
| self._initialized = False | ||
| self._device_count = 0 | ||
| self._active_devices = list() | ||
| self._handles = list() | ||
| self._active_devices = [] | ||
| self._handles = [] | ||
| self._driver = None | ||
| self._devices = list() | ||
| self._devices = [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function GPUStats.__init__ refactored with the following changes:
- Replace call to format with f-string [×2] (
use-fstring-for-formatting) - Replace list() with [] [×3] (
list-literal)
| def cli_devices(self): | ||
| """ list: List of available devices for use in faceswap's command line arguments """ | ||
| return ["{}: {}".format(idx, device) for idx, device in enumerate(self._devices)] | ||
| return [f"{idx}: {device}" for idx, device in enumerate(self._devices)] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function GPUStats.cli_devices refactored with the following changes:
- Replace call to format with f-string (
use-fstring-for-formatting)
| if not self._initialized: | ||
| if get_backend() == "amd": | ||
| self._log("debug", "AMD Detected. Using plaidMLStats") | ||
| loglevel = "INFO" if self._logger is None else self._logger.getEffectiveLevel() | ||
| self._plaid = plaidlib(log_level=loglevel, log=log) | ||
| elif IS_MACOS: | ||
| self._log("debug", "macOS Detected. Using pynvx") | ||
| try: | ||
| pynvx.cudaInit() | ||
| except RuntimeError: | ||
| self._initialized = True | ||
| return | ||
| else: | ||
| try: | ||
| self._log("debug", "OS is not macOS. Trying pynvml") | ||
| pynvml.nvmlInit() | ||
| except (pynvml.NVMLError_LibraryNotFound, # pylint: disable=no-member | ||
| if self._initialized: | ||
| return | ||
| if get_backend() == "amd": | ||
| self._log("debug", "AMD Detected. Using plaidMLStats") | ||
| loglevel = "INFO" if self._logger is None else self._logger.getEffectiveLevel() | ||
| self._plaid = plaidlib(log_level=loglevel, log=log) | ||
| elif IS_MACOS: | ||
| self._log("debug", "macOS Detected. Using pynvx") | ||
| try: | ||
| pynvx.cudaInit() | ||
| except RuntimeError: | ||
| self._initialized = True | ||
| return | ||
| else: | ||
| try: | ||
| self._log("debug", "OS is not macOS. Trying pynvml") | ||
| pynvml.nvmlInit() | ||
| except (pynvml.NVMLError_LibraryNotFound, # pylint: disable=no-member | ||
| pynvml.NVMLError_DriverNotLoaded, # pylint: disable=no-member | ||
| pynvml.NVMLError_NoPermission) as err: # pylint: disable=no-member | ||
| if plaidlib is not None: | ||
| self._log("debug", "pynvml errored. Trying plaidML") | ||
| self._plaid = plaidlib(log=log) | ||
| else: | ||
| msg = ("There was an error reading from the Nvidia Machine Learning " | ||
| "Library. Either you do not have an Nvidia GPU (in which case " | ||
| "this warning can be ignored) or the most likely cause is " | ||
| "incorrectly installed drivers. If this is the case, Please remove " | ||
| "and reinstall your Nvidia drivers before reporting." | ||
| "Original Error: {}".format(str(err))) | ||
| self._log("warning", msg) | ||
| self._initialized = True | ||
| return | ||
| except Exception as err: # pylint: disable=broad-except | ||
| msg = ("An unhandled exception occured loading pynvml. " | ||
| "Original error: {}".format(str(err))) | ||
| if self._logger: | ||
| self._logger.error(msg) | ||
| else: | ||
| print(msg) | ||
| if plaidlib is not None: | ||
| self._log("debug", "pynvml errored. Trying plaidML") | ||
| self._plaid = plaidlib(log=log) | ||
| else: | ||
| msg = f"There was an error reading from the Nvidia Machine Learning Library. Either you do not have an Nvidia GPU (in which case this warning can be ignored) or the most likely cause is incorrectly installed drivers. If this is the case, Please remove and reinstall your Nvidia drivers before reporting.Original Error: {str(err)}" | ||
|
|
||
| self._log("warning", msg) | ||
| self._initialized = True | ||
| return | ||
| self._initialized = True | ||
| self._get_device_count() | ||
| self._get_active_devices() | ||
| self._get_handles() | ||
| except Exception as err: # pylint: disable=broad-except | ||
| msg = f"An unhandled exception occured loading pynvml. Original error: {str(err)}" | ||
|
|
||
| if self._logger: | ||
| self._logger.error(msg) | ||
| else: | ||
| print(msg) | ||
| self._initialized = True | ||
| return | ||
| self._initialized = True | ||
| self._get_device_count() | ||
| self._get_active_devices() | ||
| self._get_handles() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function GPUStats._initialize refactored with the following changes:
- Add guard clause (
last-if-guard) - Replace call to format with f-string [×2] (
use-fstring-for-formatting)
| msg = "Error while reading image (TypeError): '{}'".format(filename) | ||
| msg += ". Original error message: {}".format(str(err)) | ||
| msg = ( | ||
| f"Error while reading image (TypeError): '{filename}'" | ||
| + f". Original error message: {str(err)}" | ||
| ) | ||
|
|
||
| logger.error(msg) | ||
| if raise_error: | ||
| raise Exception(msg) | ||
| except ValueError as err: | ||
| success = False | ||
| msg = ("Error while reading image. This can be caused by special characters in the " | ||
| "filename or a corrupt image file: '{}'".format(filename)) | ||
| msg += ". Original error message: {}".format(str(err)) | ||
| msg = f"Error while reading image. This can be caused by special characters in the filename or a corrupt image file: '{filename}'" | ||
|
|
||
| msg += f". Original error message: {str(err)}" | ||
| logger.error(msg) | ||
| if raise_error: | ||
| raise Exception(msg) | ||
| except Exception as err: # pylint:disable=broad-except | ||
| success = False | ||
| msg = "Failed to load image '{}'. Original Error: {}".format(filename, str(err)) | ||
| msg = f"Failed to load image '{filename}'. Original Error: {str(err)}" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function read_image refactored with the following changes:
- Replace assignment and augmented assignment with single assignment (
merge-assign-and-aug-assign) - Replace call to format with f-string [×5] (
use-fstring-for-formatting)
| retval = dict() | ||
| retval = {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function read_image_meta refactored with the following changes:
- Replace dict() with {} (
dict-literal)
| retval = length + b"iTXt" + chunk + crc | ||
| return retval | ||
| return length + b"iTXt" + chunk + crc |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function pack_to_itxt refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| tmp_filename = filename + "~" | ||
| tmp_filename = f"{filename}~" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function update_existing_metadata refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation)
| retval = png[:split] + pack_to_itxt(data) + png[split:] | ||
| return retval | ||
| return png[:split] + pack_to_itxt(data) + png[split:] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function png_write_meta refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
Sourcery Code Quality Report✅ Merging this PR will increase code quality in the affected files by 0.04%.
Here are some functions in these files that still need a tune-up:
Legend and ExplanationThe emojis denote the absolute quality of the code:
The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request. Please see our documentation here for details on how these metrics are calculated. We are actively working on this report - lots more documentation and extra metrics to come! Help us improve this quality report! |
Branch
masterrefactored by Sourcery.If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.
See our documentation here.
Run Sourcery locally
Reduce the feedback loop during development by using the Sourcery editor plugin:
Review changes via command line
To manually merge these changes, make sure you're on the
masterbranch, then run:Help us improve this pull request!