chore: ruff

This commit is contained in:
psychedelicious 2024-03-01 10:04:59 +11:00
parent ad86b29798
commit dd9daf8efb
44 changed files with 51 additions and 19 deletions

View File

@ -166,6 +166,7 @@ two configs are kept in separate sections of the config file:
... ...
""" """
from __future__ import annotations from __future__ import annotations
import os import os

View File

@ -1,4 +1,5 @@
"""Init file for download queue.""" """Init file for download queue."""
from .download_base import DownloadJob, DownloadJobStatus, DownloadQueueServiceBase, UnknownJobIDException from .download_base import DownloadJob, DownloadJobStatus, DownloadQueueServiceBase, UnknownJobIDException
from .download_default import DownloadQueueService, TqdmProgress from .download_default import DownloadQueueService, TqdmProgress

View File

@ -1,4 +1,5 @@
"""Init file for model record services.""" """Init file for model record services."""
from .model_records_base import ( # noqa F401 from .model_records_base import ( # noqa F401
DuplicateModelException, DuplicateModelException,
InvalidModelException, InvalidModelException,

View File

@ -39,7 +39,6 @@ Typical usage:
configs = store.search_by_attr(base_model='sd-2', model_type='main') configs = store.search_by_attr(base_model='sd-2', model_type='main')
""" """
import json import json
import sqlite3 import sqlite3
from math import ceil from math import ceil

View File

@ -17,8 +17,7 @@ class MigrateCallback(Protocol):
See :class:`Migration` for an example. See :class:`Migration` for an example.
""" """
def __call__(self, cursor: sqlite3.Cursor) -> None: def __call__(self, cursor: sqlite3.Cursor) -> None: ...
...
class MigrationError(RuntimeError): class MigrationError(RuntimeError):

View File

@ -1,6 +1,7 @@
""" """
Initialization file for invokeai.backend.image_util methods. Initialization file for invokeai.backend.image_util methods.
""" """
from .patchmatch import PatchMatch # noqa: F401 from .patchmatch import PatchMatch # noqa: F401
from .pngwriter import PngWriter, PromptFormatter, retrieve_metadata, write_metadata # noqa: F401 from .pngwriter import PngWriter, PromptFormatter, retrieve_metadata, write_metadata # noqa: F401
from .seamless import configure_model_padding # noqa: F401 from .seamless import configure_model_padding # noqa: F401

View File

@ -3,6 +3,7 @@ This module defines a singleton object, "invisible_watermark" that
wraps the invisible watermark model. It respects the global "invisible_watermark" wraps the invisible watermark model. It respects the global "invisible_watermark"
configuration variable, that allows the watermarking to be supressed. configuration variable, that allows the watermarking to be supressed.
""" """
import cv2 import cv2
import numpy as np import numpy as np
from imwatermark import WatermarkEncoder from imwatermark import WatermarkEncoder

View File

@ -4,6 +4,7 @@ wraps the actual patchmatch object. It respects the global
"try_patchmatch" attribute, so that patchmatch loading can "try_patchmatch" attribute, so that patchmatch loading can
be suppressed or deferred be suppressed or deferred
""" """
import numpy as np import numpy as np
import invokeai.backend.util.logging as logger import invokeai.backend.util.logging as logger

View File

@ -6,6 +6,7 @@ PngWriter -- Converts Images generated by T2I into PNGs, finds
Exports function retrieve_metadata(path) Exports function retrieve_metadata(path)
""" """
import json import json
import os import os
import re import re

View File

@ -3,6 +3,7 @@ This module defines a singleton object, "safety_checker" that
wraps the safety_checker model. It respects the global "nsfw_checker" wraps the safety_checker model. It respects the global "nsfw_checker"
configuration variable, that allows the checker to be supressed. configuration variable, that allows the checker to be supressed.
""" """
import numpy as np import numpy as np
from PIL import Image from PIL import Image

View File

@ -1,6 +1,7 @@
""" """
Check that the invokeai_root is correctly configured and exit if not. Check that the invokeai_root is correctly configured and exit if not.
""" """
import sys import sys
from invokeai.app.services.config import InvokeAIAppConfig from invokeai.app.services.config import InvokeAIAppConfig

View File

@ -1,4 +1,5 @@
"""Utility (backend) functions used by model_install.py""" """Utility (backend) functions used by model_install.py"""
from logging import Logger from logging import Logger
from pathlib import Path from pathlib import Path
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional

View File

@ -1,4 +1,5 @@
"""Re-export frequently-used symbols from the Model Manager backend.""" """Re-export frequently-used symbols from the Model Manager backend."""
from .config import ( from .config import (
AnyModel, AnyModel,
AnyModelConfig, AnyModelConfig,

View File

@ -19,6 +19,7 @@ Typical usage:
Validation errors will raise an InvalidModelConfigException error. Validation errors will raise an InvalidModelConfigException error.
""" """
import time import time
from enum import Enum from enum import Enum
from typing import Literal, Optional, Type, Union from typing import Literal, Optional, Type, Union

View File

@ -15,7 +15,7 @@
# #
# Adapted for use in InvokeAI by Lincoln Stein, July 2023 # Adapted for use in InvokeAI by Lincoln Stein, July 2023
# #
""" Conversion script for the Stable Diffusion checkpoints.""" """Conversion script for the Stable Diffusion checkpoints."""
import re import re
from contextlib import nullcontext from contextlib import nullcontext

View File

@ -2,6 +2,7 @@
""" """
Init file for the model loader. Init file for the model loader.
""" """
from importlib import import_module from importlib import import_module
from pathlib import Path from pathlib import Path

View File

@ -1,6 +1,7 @@
""" """
Disk-based converted model cache. Disk-based converted model cache.
""" """
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from pathlib import Path from pathlib import Path

View File

@ -14,6 +14,7 @@ Use like this:
).load_model(model_config, submodel_type) ).load_model(model_config, submodel_type)
""" """
import hashlib import hashlib
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from pathlib import Path from pathlib import Path

View File

@ -1,7 +1,6 @@
# Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Class for LoRA model loading in InvokeAI.""" """Class for LoRA model loading in InvokeAI."""
from logging import Logger from logging import Logger
from pathlib import Path from pathlib import Path
from typing import Optional, Tuple from typing import Optional, Tuple

View File

@ -1,7 +1,6 @@
# Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Class for StableDiffusion model loading in InvokeAI.""" """Class for StableDiffusion model loading in InvokeAI."""
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional

View File

@ -1,7 +1,6 @@
# Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Class for TI model loading in InvokeAI.""" """Class for TI model loading in InvokeAI."""
from pathlib import Path from pathlib import Path
from typing import Optional, Tuple from typing import Optional, Tuple

View File

@ -18,6 +18,7 @@ assert isinstance(data, CivitaiMetadata)
if data.allow_commercial_use: if data.allow_commercial_use:
print("Commercial use of this model is allowed") print("Commercial use of this model is allowed")
""" """
from .fetch import CivitaiMetadataFetch, HuggingFaceMetadataFetch, ModelMetadataFetchBase from .fetch import CivitaiMetadataFetch, HuggingFaceMetadataFetch, ModelMetadataFetchBase
from .metadata_base import ( from .metadata_base import (
AnyModelRepoMetadata, AnyModelRepoMetadata,

View File

@ -1,5 +1,6 @@
# Copyright (c) 2024 Ryan Dick, Lincoln D. Stein, and the InvokeAI Development Team # Copyright (c) 2024 Ryan Dick, Lincoln D. Stein, and the InvokeAI Development Team
"""These classes implement model patching with LoRAs and Textual Inversions.""" """These classes implement model patching with LoRAs and Textual Inversions."""
from __future__ import annotations from __future__ import annotations
import pickle import pickle

View File

@ -1,6 +1,7 @@
""" """
Initialization file for the invokeai.backend.stable_diffusion package Initialization file for the invokeai.backend.stable_diffusion package
""" """
from .diffusers_pipeline import PipelineIntermediateState, StableDiffusionGeneratorPipeline # noqa: F401 from .diffusers_pipeline import PipelineIntermediateState, StableDiffusionGeneratorPipeline # noqa: F401
from .diffusion import InvokeAIDiffuserComponent # noqa: F401 from .diffusion import InvokeAIDiffuserComponent # noqa: F401
from .diffusion.cross_attention_map_saving import AttentionMapSaver # noqa: F401 from .diffusion.cross_attention_map_saving import AttentionMapSaver # noqa: F401

View File

@ -1,6 +1,7 @@
""" """
Initialization file for invokeai.models.diffusion Initialization file for invokeai.models.diffusion
""" """
from .cross_attention_control import InvokeAICrossAttentionMixin # noqa: F401 from .cross_attention_control import InvokeAICrossAttentionMixin # noqa: F401
from .cross_attention_map_saving import AttentionMapSaver # noqa: F401 from .cross_attention_map_saving import AttentionMapSaver # noqa: F401
from .shared_invokeai_diffusion import InvokeAIDiffuserComponent # noqa: F401 from .shared_invokeai_diffusion import InvokeAIDiffuserComponent # noqa: F401

View File

@ -1,4 +1,5 @@
""" """
Initialization file for invokeai.backend.training Initialization file for invokeai.backend.training
""" """
from .textual_inversion_training import do_textual_inversion_training, parse_args # noqa: F401 from .textual_inversion_training import do_textual_inversion_training, parse_args # noqa: F401

View File

@ -858,9 +858,9 @@ def do_textual_inversion_training(
# Let's make sure we don't update any embedding weights besides the newly added token # Let's make sure we don't update any embedding weights besides the newly added token
index_no_updates = torch.arange(len(tokenizer)) != placeholder_token_id index_no_updates = torch.arange(len(tokenizer)) != placeholder_token_id
with torch.no_grad(): with torch.no_grad():
accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[ accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[index_no_updates] = (
index_no_updates orig_embeds_params[index_no_updates]
] = orig_embeds_params[index_no_updates] )
# Checks if the accelerator has performed an optimization step behind the scenes # Checks if the accelerator has performed an optimization step behind the scenes
if accelerator.sync_gradients: if accelerator.sync_gradients:

View File

@ -1,6 +1,7 @@
""" """
Initialization file for invokeai.backend.util Initialization file for invokeai.backend.util
""" """
from .attention import auto_detect_slice_size # noqa: F401 from .attention import auto_detect_slice_size # noqa: F401
from .devices import ( # noqa: F401 from .devices import ( # noqa: F401
CPU_DEVICE, CPU_DEVICE,

View File

@ -3,6 +3,7 @@
Utility routine used for autodetection of optimal slice size Utility routine used for autodetection of optimal slice size
for attention mechanism. for attention mechanism.
""" """
import psutil import psutil
import torch import torch

View File

@ -1,4 +1,5 @@
"""Context class to silence transformers and diffusers warnings.""" """Context class to silence transformers and diffusers warnings."""
import warnings import warnings
from typing import Any from typing import Any

View File

@ -340,14 +340,17 @@ def download_with_resume(url: str, dest: Path, access_token: str = None) -> Path
logger.error(f"ERROR DOWNLOADING {url}: {resp.text}") logger.error(f"ERROR DOWNLOADING {url}: {resp.text}")
return None return None
with open(dest, open_mode) as file, tqdm( with (
open(dest, open_mode) as file,
tqdm(
desc=str(dest), desc=str(dest),
initial=exist_size, initial=exist_size,
total=content_length, total=content_length,
unit="iB", unit="iB",
unit_scale=True, unit_scale=True,
unit_divisor=1000, unit_divisor=1000,
) as bar: ) as bar,
):
for data in resp.iter_content(chunk_size=1024): for data in resp.iter_content(chunk_size=1024):
size = file.write(data) size = file.write(data)
bar.update(size) bar.update(size)

View File

@ -1,4 +1,5 @@
""" """
Initialization file for invokeai.frontend.CLI Initialization file for invokeai.frontend.CLI
""" """
from .CLI import main as invokeai_command_line_interface # noqa: F401 from .CLI import main as invokeai_command_line_interface # noqa: F401

View File

@ -1,6 +1,7 @@
""" """
Wrapper for invokeai.backend.configure.invokeai_configure Wrapper for invokeai.backend.configure.invokeai_configure
""" """
from ...backend.install.invokeai_configure import main as invokeai_configure # noqa: F401 from ...backend.install.invokeai_configure import main as invokeai_configure # noqa: F401
__all__ = ["invokeai_configure"] __all__ = ["invokeai_configure"]

View File

@ -2,6 +2,7 @@
Minimalist updater script. Prompts user for the tag or branch to update to and runs Minimalist updater script. Prompts user for the tag or branch to update to and runs
pip install <path_to_git_source>. pip install <path_to_git_source>.
""" """
import os import os
import platform import platform
from distutils.version import LooseVersion from distutils.version import LooseVersion

View File

@ -1,6 +1,7 @@
""" """
Widget class definitions used by model_select.py, merge_diffusers.py and textual_inversion.py Widget class definitions used by model_select.py, merge_diffusers.py and textual_inversion.py
""" """
import curses import curses
import math import math
import os import os

View File

@ -1,4 +1,5 @@
""" """
Initialization file for invokeai.frontend.merge Initialization file for invokeai.frontend.merge
""" """
from .merge_diffusers import main as invokeai_merge_diffusers # noqa: F401 from .merge_diffusers import main as invokeai_merge_diffusers # noqa: F401

View File

@ -4,6 +4,7 @@ used to merge 2-3 models together and create a new InvokeAI-registered diffusion
Copyright (c) 2023 Lincoln Stein and the InvokeAI Development Team Copyright (c) 2023 Lincoln Stein and the InvokeAI Development Team
""" """
import argparse import argparse
import curses import curses
import re import re

View File

@ -1,4 +1,5 @@
""" """
Initialization file for invokeai.frontend.training Initialization file for invokeai.frontend.training
""" """
from .textual_inversion import main as invokeai_textual_inversion # noqa: F401 from .textual_inversion import main as invokeai_textual_inversion # noqa: F401

View File

@ -6,7 +6,6 @@ This is the frontend to "textual_inversion_training.py".
Copyright (c) 2023-24 Lincoln Stein and the InvokeAI Development Team Copyright (c) 2023-24 Lincoln Stein and the InvokeAI Development Team
""" """
import os import os
import re import re
import shutil import shutil

View File

@ -1,6 +1,7 @@
""" """
initialization file for invokeai initialization file for invokeai
""" """
from .invokeai_version import __version__ # noqa: F401 from .invokeai_version import __version__ # noqa: F401
__app_id__ = "invoke-ai/InvokeAI" __app_id__ = "invoke-ai/InvokeAI"

View File

@ -1,4 +1,5 @@
"""Test the queued download facility""" """Test the queued download facility"""
import re import re
import time import time
from pathlib import Path from pathlib import Path

View File

@ -1,6 +1,7 @@
""" """
Test model metadata fetching and storage. Test model metadata fetching and storage.
""" """
import datetime import datetime
from pathlib import Path from pathlib import Path

View File

@ -1,6 +1,7 @@
""" """
Test interaction of logging with configuration system. Test interaction of logging with configuration system.
""" """
import io import io
import logging import logging
import re import re

View File

@ -2,6 +2,7 @@
Not really a test, but a way to verify that the paths are existing Not really a test, but a way to verify that the paths are existing
and fail early if they are not. and fail early if they are not.
""" """
import pathlib import pathlib
import unittest import unittest
from os import path as osp from os import path as osp