repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
InvokeAI | invokeai/backend/patches/layers/base_layer_patch.py | .py | from abc import ABC, abstractmethod
import torch
class BaseLayerPatch(ABC):
@abstractmethod
def get_parameters(self, orig_parameters: dict[str, torch.Tensor], weight: float) -> dict[str, torch.Tensor]:
"""Get the parameter residual updates that should be applied to the original parameters. Parameters... | 23 | 735 |
InvokeAI | invokeai/backend/patches/layers/lokr_layer.py | .py | from typing import Dict
import torch
from invokeai.backend.patches.layers.lora_layer_base import LoRALayerBase
from invokeai.backend.util.calc_tensor_size import calc_tensors_size
class LoKRLayer(LoRALayerBase):
"""LoKR LyCoris layer.
Example model for testing this layer type: https://civitai.com/models/34... | 128 | 4,353 |
InvokeAI | invokeai/backend/patches/layers/set_parameter_layer.py | .py | import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.util.calc_tensor_size import calc_tensor_size
class SetParameterLayer(BaseLayerPatch):
"""A layer that sets a single parameter to a new target value.
(The diff between the target value and current v... | 28 | 1,118 |
InvokeAI | invokeai/backend/patches/layers/flux_control_lora_layer.py | .py | import torch
from invokeai.backend.patches.layers.lora_layer import LoRALayer
class FluxControlLoRALayer(LoRALayer):
"""A special case of LoRALayer for use with FLUX Control LoRAs that pads the target parameter with zeros if the
shapes don't match.
"""
def get_parameters(self, orig_parameters: dict[... | 20 | 753 |
InvokeAI | invokeai/backend/patches/layers/ia3_layer.py | .py | from typing import Dict, Optional
import torch
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.cast_to_device import cast_to_device
from invokeai.backend.patches.layers.lora_layer_base import LoRALayerBase
class IA3Layer(LoRALayerBase):
"""IA3 Layer
Example model for testing this... | 60 | 1,889 |
InvokeAI | invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py | .py | """Qwen Image LoRA conversion utilities.
Qwen Image uses QwenImageTransformer2DModel architecture.
Supports multiple LoRA formats:
- Diffusers/PEFT: transformer_blocks.0.attn.to_k.lora_down.weight
- With prefix: transformer.transformer_blocks.0.attn.to_k.lora_down.weight
- Kohya: lora_unet_transformer_blocks_0_attn_to... | 198 | 7,142 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_diffusers_lora_conversion_utils.py | .py | from typing import Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_co... | 385 | 17,072 |
InvokeAI | invokeai/backend/patches/lora_conversions/formats.py | .py | from typing import Any
from invokeai.backend.model_manager.taxonomy import FluxLoRAFormat
from invokeai.backend.patches.lora_conversions.flux_aitoolkit_lora_conversion_utils import (
is_state_dict_likely_in_flux_aitoolkit_format,
)
from invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils ... | 50 | 2,254 |
InvokeAI | invokeai/backend/patches/lora_conversions/krea2_lora_constants.py | .py | # Krea-2 LoRA prefix constants.
# These prefixes namespace LoRA patch keys when applying them to Krea-2 models.
# Prefix for Krea-2 transformer (Krea2Transformer2DModel) LoRA layers.
KREA2_LORA_TRANSFORMER_PREFIX = "lora_transformer-"
# Prefix for Krea-2 Qwen3-VL text encoder LoRA layers.
KREA2_LORA_QWEN3VL_PREFIX = ... | 9 | 336 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_lora_constants.py | .py | # Prefixes used to distinguish between transformer and CLIP text encoder keys in the FLUX InvokeAI LoRA format.
FLUX_LORA_TRANSFORMER_PREFIX = "lora_transformer-"
FLUX_LORA_CLIP_PREFIX = "lora_clip-"
FLUX_LORA_T5_PREFIX = "lora_t5-"
| 5 | 233 |
InvokeAI | invokeai/backend/patches/lora_conversions/sd_lora_conversion_utils.py | .py | from typing import Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
def lora_model_from_sd_state_dict(state_dict: Dict[str,... | 30 | 1,058 |
InvokeAI | invokeai/backend/patches/lora_conversions/z_image_lora_constants.py | .py | # Z-Image LoRA prefix constants
# These prefixes are used for key mapping when applying LoRA patches to Z-Image models
# Prefix for Z-Image transformer (S3-DiT architecture) LoRA layers
Z_IMAGE_LORA_TRANSFORMER_PREFIX = "lora_transformer-"
# Prefix for Qwen3 text encoder LoRA layers
Z_IMAGE_LORA_QWEN3_PREFIX = "lora_... | 9 | 328 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_kohya_lora_conversion_utils.py | .py | import re
from typing import Any, Dict, TypeVar
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.flux_lora_constants import (
FLUX_LORA_CLIP_PREFI... | 185 | 8,134 |
InvokeAI | invokeai/backend/patches/lora_conversions/wan_lora_conversion_utils.py | .py | """Wan 2.2 LoRA conversion utilities.
Wan LoRAs target the ``WanTransformer3DModel`` attention and FFN layers. We
normalise every supported source layout to the diffusers parameter-path naming
the loaded model uses at runtime (``blocks.<idx>.attn1.to_q``,
``blocks.<idx>.attn2.to_k``, ``blocks.<idx>.ffn.net.0.proj``, e... | 251 | 9,439 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_onetrainer_lora_conversion_utils.py | .py | import re
from typing import Any, Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.flux_diffusers_lora_conversion_utils import (
lora_layers_... | 165 | 7,131 |
InvokeAI | invokeai/backend/patches/lora_conversions/anima_lora_constants.py | .py | # Anima LoRA prefix constants
# These prefixes are used for key mapping when applying LoRA patches to Anima models
import re
# Prefix for Anima transformer (Cosmos DiT architecture) LoRA layers
ANIMA_LORA_TRANSFORMER_PREFIX = "lora_transformer-"
# Prefix for Qwen3 text encoder LoRA layers
ANIMA_LORA_QWEN3_PREFIX = "... | 88 | 4,211 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_xlabs_lora_conversion_utils.py | .py | import re
from typing import Any, Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
from i... | 93 | 3,803 |
InvokeAI | invokeai/backend/patches/lora_conversions/z_image_lora_conversion_utils.py | .py | """Z-Image LoRA conversion utilities.
Z-Image uses S3-DiT transformer architecture with Qwen3 text encoder.
LoRAs for Z-Image typically follow the diffusers PEFT format or Kohya format.
"""
import re
from typing import Any, Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatc... | 261 | 9,595 |
InvokeAI | invokeai/backend/patches/lora_conversions/wan_lora_constants.py | .py | # Wan 2.2 LoRA prefix constants and key-shape detection helpers.
#
# Wan LoRAs come in three shapes in the wild:
#
# 1. **Diffusers PEFT** (HF naming), with or without a "transformer." prefix:
# blocks.0.attn1.to_q.lora_A.weight
# transformer.blocks.0.attn1.to_q.lora_A.weight
#
# 2. **Native upstream PEFT** (... | 175 | 7,752 |
InvokeAI | invokeai/backend/patches/lora_conversions/peft_adapter_utils.py | .py | """Utilities for handling PEFT named-adapter LoRA state dicts.
PEFT (HuggingFace Parameter-Efficient Fine-Tuning) supports multiple named adapters per model.
When saved, the adapter name is encoded in the weight key:
Standard PEFT: foo.bar.lora_A.weight
Named-adapter PEFT: foo.bar.lora_A.<adapt... | 73 | 3,037 |
InvokeAI | invokeai/backend/patches/lora_conversions/kohya_key_utils.py | .py | from typing import Iterable
INDEX_PLACEHOLDER = "index_placeholder"
# Type alias for a 'ParsingTree', which is a recursive dict with string keys.
ParsingTree = dict[str, "ParsingTree"]
def insert_periods_into_kohya_key(key: str, parsing_tree: ParsingTree) -> str:
"""Insert periods into a Kohya key based on a p... | 103 | 2,846 |
InvokeAI | invokeai/backend/patches/lora_conversions/krea2_lora_conversion_utils.py | .py | """Krea-2 LoRA conversion utilities.
Krea-2 uses a single-stream MMDiT (``Krea2Transformer2DModel``) with a Qwen3-VL text encoder.
Published LoRAs (e.g. krea/Krea-2-LoRA-*) are diffusers PEFT format: keys like
``transformer.<module>.lora_A.weight`` / ``lora_B.weight``. The distinctive Krea-2 module is the
``text_fusio... | 235 | 10,729 |
InvokeAI | invokeai/backend/patches/lora_conversions/sdxl_lora_conversion_utils.py | .py | import bisect
from typing import Dict, List, Tuple, TypeVar
T = TypeVar("T")
def convert_sdxl_keys_to_diffusers_format(state_dict: Dict[str, T]) -> dict[str, T]:
"""Convert the keys of an SDXL LoRA state_dict to diffusers format.
The input state_dict can be in either Stability AI format or diffusers format.... | 155 | 6,942 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_control_lora_utils.py | .py | import re
from typing import Any, Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.layers... | 87 | 3,804 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_onetrainer_bfl_lora_conversion_utils.py | .py | """Utilities for detecting and converting FLUX LoRAs in OneTrainer BFL format.
This format is produced by newer versions of OneTrainer and uses BFL internal key names
(double_blocks, single_blocks, img_attn, etc.) with a 'transformer.' prefix and
InvokeAI-native LoRA suffixes (lora_down.weight, lora_up.weight, alpha).... | 169 | 6,630 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_aitoolkit_lora_conversion_utils.py | .py | import json
from dataclasses import dataclass, field
from typing import Any
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.flux_diffusers_lora_conve... | 103 | 3,815 |
InvokeAI | invokeai/backend/patches/lora_conversions/anima_lora_conversion_utils.py | .py | """Anima LoRA conversion utilities.
Anima uses a Cosmos Predict2 DiT transformer architecture.
LoRAs for Anima typically follow the Kohya-style format with underscore-separated keys
(e.g., lora_unet_blocks_0_cross_attn_k_proj) that map to model parameter paths
(e.g., blocks.0.cross_attn.k_proj).
Some Anima LoRAs also... | 301 | 10,915 |
InvokeAI | invokeai/backend/patches/lora_conversions/flux_bfl_peft_lora_conversion_utils.py | .py | """Utilities for detecting and converting FLUX LoRAs in BFL PEFT format.
This format uses BFL internal key names (double_blocks, single_blocks, etc.) with a
'diffusion_model.' prefix and PEFT-style LoRA suffixes (lora_A.weight, lora_B.weight).
LyCORIS variants (LoKR, LoHA, etc.) are also supported, using their respect... | 540 | 20,681 |
InvokeAI | invokeai/backend/anima/control_net_lllite.py | .py | """ControlNet-LLLite adapter for Anima (DiT), v2 weight format.
A LLLite adapter is a shared conv trunk (``conditioning1``) that encodes a
conditioning image into per-token embeddings, plus one tiny zero-init MLP per
target Linear in the DiT. Each module perturbs its Linear's *input*:
``y = org_forward(x + up(film_mlp... | 554 | 23,068 |
InvokeAI | invokeai/backend/anima/__init__.py | .py | """Anima model backend module.
Anima is a 2B-parameter anime-focused text-to-image model built on NVIDIA's
Cosmos Predict2 DiT architecture with a custom LLM Adapter that bridges Qwen3
0.6B text encoder outputs to the DiT backbone.
"""
| 7 | 237 |
InvokeAI | invokeai/backend/anima/regional_prompting.py | .py | """Regional prompting extension for Anima.
Anima's architecture uses separate cross-attention in each DiT block: image tokens
(in 5D spatial layout) cross-attend to context tokens (LLM Adapter output). This is
different from Z-Image's unified [img, txt] sequence with self-attention.
For regional prompting, we:
1. Run... | 174 | 6,891 |
InvokeAI | invokeai/backend/anima/anima_transformer_patch.py | .py | """Utilities for patching the AnimaTransformer to support regional cross-attention masks."""
from contextlib import contextmanager
from typing import Optional
import torch
import torch.nn.functional as F
from einops import rearrange
from invokeai.backend.anima.regional_prompting import AnimaRegionalPromptingExtensio... | 107 | 4,146 |
InvokeAI | invokeai/backend/anima/conditioning_data.py | .py | """Anima text conditioning data structures.
Anima uses a dual-conditioning scheme:
- Qwen3 0.6B hidden states (continuous embeddings)
- T5-XXL token IDs (discrete IDs, embedded by the LLM Adapter inside the transformer)
Both are produced by the text encoder invocation and stored together.
For regional prompting, mul... | 65 | 2,621 |
InvokeAI | invokeai/backend/anima/anima_transformer.py | .py | """Anima transformer model: Cosmos Predict2 MiniTrainDIT + LLM Adapter.
The Anima architecture combines:
1. MiniTrainDIT: A Cosmos Predict2 DiT backbone with 28 blocks, 2048-dim hidden state,
and 3D RoPE positional embeddings.
2. LLMAdapter: A 6-layer cross-attention transformer that fuses Qwen3 0.6B hidden states
... | 1,041 | 40,326 |
InvokeAI | invokeai/backend/anima/scheduler_driver.py | .py | """Anima scheduler driver.
Encapsulates the per-scheduler API quirks that ``anima_denoise._run_diffusion``
would otherwise have to know about:
* Schedulers that accept ``set_timesteps(sigmas=...)`` get the pre-shifted
Anima schedule passed directly.
* Schedulers that don't accept ``sigmas=`` use ``set_begin_index()... | 151 | 6,083 |
InvokeAI | invokeai/backend/onnx/onnx_runtime.py | .py | # Copyright (c) 2024 The InvokeAI Development Team
import os
import sys
from pathlib import Path
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import onnx
import torch
from onnx import numpy_helper
from onnxruntime import InferenceSession, SessionOptions, get_available_providers
from invokea... | 224 | 9,341 |
InvokeAI | invokeai/backend/util/build_line.py | .py | from typing import Callable
def build_line(x1: float, y1: float, x2: float, y2: float) -> Callable[[float], float]:
"""Build a linear function given two points on the line (x1, y1) and (x2, y2)."""
return lambda x: (y2 - y1) / (x2 - x1) * (x - x1) + y1
| 7 | 263 |
InvokeAI | invokeai/backend/util/prefix_logger_adapter.py | .py | import logging
from typing import Any, MutableMapping
# Issue with type hints related to LoggerAdapter: https://github.com/python/typeshed/issues/7855
class PrefixedLoggerAdapter(logging.LoggerAdapter): # type: ignore
def __init__(self, logger: logging.Logger, prefix: str):
super().__init__(logger, {})
... | 13 | 504 |
InvokeAI | invokeai/backend/util/logging.py | .py | # Copyright (c) 2023 Lincoln D. Stein and The InvokeAI Development Team
"""
Logging class for InvokeAI that produces console messages.
Usage:
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger(name='InvokeAI') // Initialization
(or)
logger = InvokeAILogger.get_logger(__name_... | 436 | 14,792 |
InvokeAI | invokeai/backend/util/hotfixes.py | .py | from typing import Any, Dict, List, Optional, Tuple, Union
import diffusers
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.loaders.single_file_model import FromOriginalModelMixin
from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor
fr... | 845 | 40,978 |
InvokeAI | invokeai/backend/util/fp8.py | .py | """Helpers for models loaded with FP8 layerwise-casting storage.
See `ModelLoader._apply_fp8_layerwise_casting`: eligible layers keep their weights in
`float8_e4m3fn` and forward hooks cast them up to the model's compute dtype (fp16/bf16) for the
duration of each forward pass.
The consequence for callers is that `mod... | 75 | 3,850 |
InvokeAI | invokeai/backend/util/attention.py | .py | # Copyright (c) 2023 Lincoln Stein and the InvokeAI Team
"""
Utility routine used for autodetection of optimal slice size
for attention mechanism.
"""
import psutil
import torch
from invokeai.backend.util.devices import TorchDevice
def auto_detect_slice_size(latents: torch.Tensor) -> str:
bytes_per_element_need... | 38 | 1,174 |
InvokeAI | invokeai/backend/util/catch_sigint.py | .py | """
This module defines a context manager `catch_sigint()` which temporarily replaces
the sigINT handler defined by the ASGI in order to allow the user to ^C the application
and shut it down immediately. This was implemented in order to allow the user to interrupt
slow model hashing during startup.
Use like this:
f... | 30 | 906 |
InvokeAI | invokeai/backend/util/util.py | .py | import base64
import io
import os
import re
import unicodedata
from pathlib import Path
from PIL import Image
def slugify(value: str, allow_unicode: bool = False) -> str:
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't al... | 75 | 2,355 |
InvokeAI | invokeai/backend/util/level_zero.py | .py | """Minimal Level Zero queries for facts torch does not surface on XPU.
Two things are read here, both through the Level Zero loader that is already present wherever
``torch+xpu`` is installed (it arrives with the ``intel-sycl-rt`` runtime dependency) -- so no
new package and no compiled extension:
* **Is a device int... | 326 | 12,798 |
InvokeAI | invokeai/backend/util/silence_warnings.py | .py | import warnings
from contextlib import ContextDecorator
from diffusers.utils import logging as diffusers_logging
from transformers import logging as transformers_logging
# Inherit from ContextDecorator to allow using SilenceWarnings as both a context manager and a decorator.
class SilenceWarnings(ContextDecorator):
... | 37 | 1,166 |
InvokeAI | invokeai/backend/util/mask.py | .py | import torch
def to_standard_mask_dim(mask: torch.Tensor) -> torch.Tensor:
"""Standardize the dimensions of a mask tensor.
Args:
mask (torch.Tensor): A mask tensor. The shape can be (1, h, w) or (h, w).
Returns:
torch.Tensor: The output mask tensor. The shape is (1, h, w).
"""
# ... | 54 | 1,589 |
InvokeAI | invokeai/backend/util/__init__.py | .py | """
Initialization file for invokeai.backend.util
"""
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.util import Chdir, directory_size
__all__ = [
"directory_size",
"Chdir",
"InvokeAILogger",
]
| 13 | 245 |
InvokeAI | invokeai/backend/util/vae_working_memory.py | .py | from typing import Literal
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage
from diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWan
from diffusers.models.autoencoders.autoe... | 245 | 12,095 |
InvokeAI | invokeai/backend/util/devices.py | .py | import threading
from collections import Counter, defaultdict
from typing import Dict, Literal, Optional, Union
import torch
from deprecated import deprecated
from invokeai.app.services.config.config_default import get_config
from invokeai.backend.util.level_zero import xpu_device_is_integrated, xpu_memory_info
from ... | 434 | 21,090 |
InvokeAI | invokeai/backend/util/gallery_maintenance.py | .py | # pylint: disable=line-too-long
# pylint: disable=broad-exception-caught
# pylint: disable=missing-function-docstring
"""Script to peform db maintenance and outputs directory management."""
import argparse
import datetime
import enum
import glob
import locale
import os
import shutil
import sqlite3
from pathlib import ... | 595 | 27,424 |
InvokeAI | invokeai/backend/util/device_pool.py | .py | """Process-global arbiter that lends idle generation GPUs for text-encoder offload.
In multi-GPU mode (see ``generation_devices``) the session processor runs one generation worker
per GPU. When fewer sessions are running than there are GPUs, some GPUs sit idle. This arbiter lets
a busy worker temporarily *borrow* an i... | 143 | 6,966 |
InvokeAI | invokeai/backend/util/original_weights_storage.py | .py | from __future__ import annotations
from typing import Dict, Iterator, Optional, Tuple
import torch
from invokeai.backend.util.devices import TorchDevice
class OriginalWeightsStorage:
"""A class for tracking the original weights of a model for patch/unpatch operations."""
def __init__(self, cached_weights:... | 40 | 1,406 |
InvokeAI | invokeai/backend/util/test_utils.py | .py | import contextlib
from pathlib import Path
from typing import Optional, Union
import pytest
import torch
from invokeai.app.services.model_manager import ModelManagerServiceBase
from invokeai.app.services.model_records import UnknownModelException
from invokeai.backend.model_manager.load.load_base import LoadedModel
f... | 69 | 2,677 |
InvokeAI | invokeai/backend/util/calc_tensor_size.py | .py | import torch
def calc_tensor_size(t: torch.Tensor) -> int:
"""Calculate the size of a tensor in bytes."""
# SDNQ quantized tensors advertise the dequantized shape with a uint8 dtype, which both
# over-counts the packed uint4/int5 storage and omits the scale/zero_point/svd payloads. Ask the
# wrapper f... | 19 | 858 |
InvokeAI | invokeai/backend/model_hash/model_hash.py | .py | # Copyright (c) 2023 Lincoln D. Stein and the InvokeAI Development Team
import hashlib
import os
from pathlib import Path
from typing import Callable, Literal, Optional, Union
from blake3 import blake3
from tqdm import tqdm
from invokeai.app.util.misc import uuid_string
HASHING_ALGORITHMS = Literal[
"blake3_mul... | 230 | 8,337 |
InvokeAI | invokeai/backend/model_hash/hash_validator.py | .py | import json
from base64 import b64decode
def validate_hash(hash: str):
if ":" not in hash:
return
for enc_hash in hashes:
alg, hash_ = hash.split(":")
if alg == "blake3":
alg = "blake3_single"
map = json.loads(b64decode(enc_hash))
if alg in map:
... | 27 | 11,111 |
InvokeAI | invokeai/backend/image_util/hed.py | .py | # Adapted from https://github.com/huggingface/controlnet_aux
import pathlib
import cv2
import huggingface_hub
import numpy as np
import torch
from einops import rearrange
from huggingface_hub import hf_hub_download
from PIL import Image
from invokeai.backend.image_util.util import (
nms,
normalize_image_chan... | 218 | 8,068 |
InvokeAI | invokeai/backend/image_util/lineart_anime.py | .py | """Adapted from https://github.com/huggingface/controlnet_aux (Apache-2.0 license)."""
import functools
import pathlib
from typing import Optional
import cv2
import huggingface_hub
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from huggingface_hub import hf_hub_download
from PIL i... | 275 | 10,719 |
InvokeAI | invokeai/backend/image_util/pngwriter.py | .py | """
Two helper classes for dealing with PNG images and their path names.
PngWriter -- Converts Images generated by T2I into PNGs, finds
appropriate names for them, and writes prompt metadata
into the PNG.
Exports function retrieve_metadata(path)
"""
import json
import os
import re
from PIL ... | 119 | 4,289 |
InvokeAI | invokeai/backend/image_util/util.py | .py | from math import ceil, floor, sqrt
from typing import Optional
import cv2
import numpy as np
from PIL import Image
class InitImageResizer:
"""Simple class to create resized copies of an Image while preserving the aspect ratio."""
def __init__(self, Image):
self.image = Image
def resize(self, wi... | 248 | 8,496 |
InvokeAI | invokeai/backend/image_util/__init__.py | .py | """
Initialization file for invokeai.backend.image_util methods.
"""
from invokeai.backend.image_util.infill_methods.patchmatch import PatchMatch # noqa: F401
from invokeai.backend.image_util.pngwriter import ( # noqa: F401
PngWriter,
PromptFormatter,
retrieve_metadata,
write_metadata,
)
from invokea... | 13 | 395 |
InvokeAI | invokeai/backend/image_util/controlnet_processor.py | .py | """Utilities for processing images with ControlNet processors."""
from datetime import datetime
from typing import Any, Optional
from invokeai.app.invocations.fields import ImageField
from invokeai.app.services.invoker import InvocationServices
from invokeai.app.services.session_queue.session_queue_common import Sess... | 189 | 8,015 |
InvokeAI | invokeai/backend/image_util/composition.py | .py | # TODO: Improve blend modes
# TODO: Add nodes like Hue Adjust for Saturation/Contrast/etc... ?
# TODO: Continue implementing more blend modes/color spaces(?)
# TODO: Custom ICC profiles with PIL.ImageCms?
# TODO: Blend multiple layers all crammed into a tensor(?) or list
# Copyright (c) 2023 Darren Ringer <dwringer@gm... | 123 | 5,911 |
InvokeAI | invokeai/backend/image_util/lineart.py | .py | """Adapted from https://github.com/huggingface/controlnet_aux (Apache-2.0 license)."""
import pathlib
import cv2
import huggingface_hub
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from huggingface_hub import hf_hub_download
from PIL import Image
from invokeai.backend.image_util... | 229 | 7,625 |
InvokeAI | invokeai/backend/image_util/invisible_watermark.py | .py | """
This module defines a singleton object, "invisible_watermark" that
wraps the invisible watermark model. It respects the global "invisible_watermark"
configuration variable, that allows the watermarking to be supressed.
"""
import cv2
import numpy as np
from PIL import Image
import invokeai.backend.util.logging as... | 50 | 2,078 |
InvokeAI | invokeai/backend/image_util/color_conversion.py | .py | from math import pi as PI
import torch
MAX_FLOAT = torch.finfo(torch.tensor(1.0).dtype).max
_SRGB_TO_LINEAR_THRESHOLD = 0.0404482362771082
_LINEAR_TO_SRGB_THRESHOLD = 0.0031308
_SRGB_TO_XYZ_D65_MATRIX = (
(0.4124, 0.3576, 0.1805),
(0.2126, 0.7152, 0.0722),
(0.0193, 0.1192, 0.9505),
)
_XYZ_D65_TO_SRGB_MATR... | 1,085 | 46,997 |
InvokeAI | invokeai/backend/image_util/safety_checker.py | .py | """
This module defines a singleton object, "safety_checker" that
wraps the safety_checker model. It respects the global "nsfw_checker"
configuration variable, that allows the checker to be supressed.
"""
from pathlib import Path
import numpy as np
from diffusers.pipelines.stable_diffusion.safety_checker import Stabl... | 85 | 3,445 |
InvokeAI | invokeai/backend/image_util/content_shuffle.py | .py | # Adapted from https://github.com/huggingface/controlnet_aux
import cv2
import numpy as np
from PIL import Image
from invokeai.backend.image_util.util import np_to_pil, pil_to_np
def make_noise_disk(H, W, C, F):
noise = np.random.uniform(low=0, high=1, size=((H // F) + 2, (W // F) + 2, C))
noise = cv2.resiz... | 41 | 1,229 |
InvokeAI | invokeai/backend/image_util/canny.py | .py | import cv2
from PIL import Image
from invokeai.backend.image_util.util import (
cv2_to_pil,
normalize_image_channel_count,
pil_to_cv2,
resize_image_to_resolution,
)
def get_canny_edges(
image: Image.Image, low_threshold: int, high_threshold: int, detect_resolution: int, image_resolution: int
) ->... | 42 | 1,461 |
InvokeAI | invokeai/backend/image_util/dw_openpose/utils.py | .py | # Code from the original DWPose Implementation: https://github.com/IDEA-Research/DWPose
import math
import cv2
import numpy as np
import numpy.typing as npt
eps = 0.01
NDArrayInt = npt.NDArray[np.uint8]
def draw_bodypose(canvas: NDArrayInt, candidate: NDArrayInt, subset: NDArrayInt) -> NDArrayInt:
H, W, C = ca... | 159 | 4,083 |
InvokeAI | invokeai/backend/image_util/dw_openpose/__init__.py | .py | from pathlib import Path
from typing import Dict
import huggingface_hub
import numpy as np
import onnxruntime as ort
import torch
from PIL import Image
from invokeai.backend.image_util.dw_openpose.onnxdet import inference_detector
from invokeai.backend.image_util.dw_openpose.onnxpose import inference_pose
from invoke... | 153 | 5,565 |
InvokeAI | invokeai/backend/image_util/dw_openpose/onnxdet.py | .py | # Code from the original DWPose Implementation: https://github.com/IDEA-Research/DWPose
import cv2
import numpy as np
def nms(boxes, scores, nms_thr):
"""Single class NMS implemented in Numpy."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
areas = (x2 - x1 + 1) * (y2 ... | 129 | 4,409 |
InvokeAI | invokeai/backend/image_util/dw_openpose/onnxpose.py | .py | # Code from the original DWPose Implementation: https://github.com/IDEA-Research/DWPose
from typing import List, Tuple
import cv2
import numpy as np
import onnxruntime as ort
def preprocess(
img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"... | 362 | 11,436 |
InvokeAI | invokeai/backend/image_util/depth_anything/depth_anything_pipeline.py | .py | import pathlib
from typing import Optional
import torch
from PIL import Image
from transformers import pipeline
from transformers.pipelines import DepthEstimationPipeline
from invokeai.backend.raw_model import RawModel
class DepthAnythingPipeline(RawModel):
"""Custom wrapper for the Depth Estimation pipeline fr... | 42 | 1,583 |
InvokeAI | invokeai/backend/image_util/realesrgan/realesrgan.py | .py | import math
from enum import Enum
from typing import Any, Optional
import cv2
import numpy as np
import numpy.typing as npt
import torch
from cv2.typing import MatLike
from tqdm import tqdm
from invokeai.backend.image_util.basicsr.rrdbnet_arch import RRDBNet
from invokeai.backend.model_manager.taxonomy import AnyMode... | 273 | 10,625 |
InvokeAI | invokeai/backend/image_util/infill_methods/mosaic.py | .py | from typing import Tuple
import numpy as np
from PIL import Image
def infill_mosaic(
image: Image.Image,
tile_shape: Tuple[int, int] = (64, 64),
min_color: Tuple[int, int, int, int] = (0, 0, 0, 0),
max_color: Tuple[int, int, int, int] = (255, 255, 255, 0),
) -> Image.Image:
"""
image:PIL - A ... | 61 | 2,412 |
InvokeAI | invokeai/backend/image_util/infill_methods/lama.py | .py | from pathlib import Path
from typing import Any
import numpy as np
import torch
from PIL import Image
import invokeai.backend.util.logging as logger
from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.model_manager.taxonomy import AnyModel
def norm_img(np_img... | 55 | 1,802 |
InvokeAI | invokeai/backend/image_util/infill_methods/patchmatch.py | .py | """
This module defines a singleton object, "patchmatch" that
wraps the actual patchmatch object. It respects the global
"try_patchmatch" attribute, so that patchmatch loading can
be suppressed or deferred
"""
import numpy as np
from PIL import Image
import invokeai.backend.util.logging as logger
from invokeai.app.se... | 68 | 1,933 |
InvokeAI | invokeai/backend/image_util/infill_methods/cv2_inpaint.py | .py | import cv2
import numpy as np
from PIL import Image
def cv2_inpaint(image: Image.Image) -> Image.Image:
# Prepare Image
image_array = np.array(image.convert("RGB"))
image_cv = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)
# Prepare Mask From Alpha Channel
mask = image.split()[3].convert("RGB")
... | 21 | 662 |
InvokeAI | invokeai/backend/image_util/infill_methods/tile.py | .py | from dataclasses import dataclass
from typing import Optional
import numpy as np
from PIL import Image
def create_tile_pool(img_array: np.ndarray, tile_size: tuple[int, int]) -> list[np.ndarray]:
"""
Create a pool of tiles from non-transparent areas of the image by systematically walking through the image.
... | 123 | 4,339 |
InvokeAI | invokeai/backend/image_util/mlsd/utils.py | .py | '''
modified by lihaoweicv
pytorch version
'''
'''
M-LSD
Copyright 2021-present NAVER Corp.
Apache License v2.0
'''
import cv2
import numpy as np
import torch
from torch.nn import functional as F
from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
def deccode_output_score_and_pt... | 590 | 24,460 |
InvokeAI | invokeai/backend/image_util/mlsd/__init__.py | .py | # Adapted from https://github.com/huggingface/controlnet_aux
import pathlib
import cv2
import huggingface_hub
import numpy as np
import torch
from PIL import Image
from invokeai.backend.image_util.mlsd.models.mbv2_mlsd_large import MobileV2_MLSD_Large
from invokeai.backend.image_util.mlsd.utils import pred_lines
fro... | 67 | 2,312 |
InvokeAI | invokeai/backend/image_util/mlsd/models/mbv2_mlsd_large.py | .py | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from torch.nn import functional as F
class BlockTypeA(nn.Module):
def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True):
super(BlockTypeA, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_c... | 291 | 9,656 |
InvokeAI | invokeai/backend/image_util/mlsd/models/mbv2_mlsd_tiny.py | .py | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from torch.nn import functional as F
class BlockTypeA(nn.Module):
def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True):
super(BlockTypeA, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_c... | 274 | 9,158 |
InvokeAI | invokeai/backend/image_util/imwatermark/vendor.py | .py | # This file is vendored from https://github.com/ShieldMnt/invisible-watermark
#
# `invisible-watermark` is MIT licensed as of August 23, 2025, when the code was copied into this repo.
#
# Why we vendored it in:
# `invisible-watermark` has a dependency on `opencv-python`, which conflicts with Invoke's dependency on
# `o... | 311 | 10,406 |
InvokeAI | invokeai/backend/image_util/grounding_dino/grounding_dino_pipeline.py | .py | from typing import Optional
import torch
from PIL import Image
from transformers.pipelines import ZeroShotObjectDetectionPipeline
from invokeai.backend.image_util.grounding_dino.detection_result import DetectionResult
from invokeai.backend.raw_model import RawModel
class GroundingDinoPipeline(RawModel):
"""A wr... | 38 | 1,600 |
InvokeAI | invokeai/backend/image_util/grounding_dino/detection_result.py | .py | from pydantic import BaseModel, ConfigDict
class BoundingBox(BaseModel):
"""Bounding box helper class."""
xmin: int
ymin: int
xmax: int
ymax: int
class DetectionResult(BaseModel):
"""Detection result from Grounding DINO."""
score: float
label: str
box: BoundingBox
model_con... | 23 | 455 |
InvokeAI | invokeai/backend/image_util/pbr_maps/pbr_maps.py | .py | # Original: https://github.com/joeyballentine/Material-Map-Generator
# Adopted and optimized for Invoke AI
import pathlib
from typing import Any, Literal
import cv2
import numpy as np
import numpy.typing as npt
import torch
from PIL import Image
from safetensors.torch import load_file
from invokeai.backend.image_uti... | 142 | 5,446 |
InvokeAI | invokeai/backend/image_util/pbr_maps/architecture/pbr_rrdb_net.py | .py | # Original: https://github.com/joeyballentine/Material-Map-Generator
# Adopted and optimized for Invoke AI
import math
from typing import Literal, Optional
import torch
import torch.nn as nn
import invokeai.backend.image_util.pbr_maps.architecture.block as B
UPSCALE_MODE = Literal["upconv", "pixelshuffle"]
class ... | 71 | 2,214 |
InvokeAI | invokeai/backend/image_util/pbr_maps/architecture/block.py | .py | # Original: https://github.com/joeyballentine/Material-Map-Generator
# Adopted and optimized for Invoke AI
from collections import OrderedDict
from typing import Any, List, Literal, Optional
import torch
import torch.nn as nn
ACTIVATION_LAYER_TYPE = Literal["relu", "leakyrelu", "prelu"]
NORMALIZATION_LAYER_TYPE = Li... | 368 | 11,483 |
InvokeAI | invokeai/backend/image_util/pbr_maps/utils/image_ops.py | .py | # Original: https://github.com/joeyballentine/Material-Map-Generator
# Adopted and optimized for Invoke AI
import math
from typing import Any, Callable, List
import numpy as np
import numpy.typing as npt
from invokeai.backend.image_util.pbr_maps.architecture.pbr_rrdb_net import PBR_RRDB_Net
def crop_seamless(img: ... | 94 | 3,480 |
InvokeAI | invokeai/backend/image_util/segment_anything/segment_anything_2_pipeline.py | .py | from typing import Optional
import torch
from PIL import Image
# Import SAM2 components - these should be available in transformers 4.56.0+
from transformers.models.sam2 import Sam2Model
from transformers.models.sam2.processing_sam2 import Sam2Processor
from invokeai.backend.image_util.segment_anything.shared import... | 110 | 3,996 |
InvokeAI | invokeai/backend/image_util/segment_anything/segment_anything_pipeline.py | .py | from typing import Optional
import torch
from PIL import Image
from transformers.models.sam import SamModel
from transformers.models.sam.processing_sam import SamProcessor
from invokeai.backend.image_util.segment_anything.shared import SAMInput
from invokeai.backend.raw_model import RawModel
class SegmentAnythingPi... | 98 | 3,597 |
InvokeAI | invokeai/backend/image_util/segment_anything/shared.py | .py | from enum import Enum
from pydantic import BaseModel, model_validator
from pydantic.fields import Field
class BoundingBox(BaseModel):
x_min: int = Field(..., description="The minimum x-coordinate of the bounding box (inclusive).")
x_max: int = Field(..., description="The maximum x-coordinate of the bounding ... | 50 | 1,997 |
InvokeAI | invokeai/backend/image_util/segment_anything/mask_refinement.py | .py | # This file contains utilities for Grounded-SAM mask refinement based on:
# https://github.com/NielsRogge/Transformers-Tutorials/blob/a39f33ac1557b02ebfb191ea7753e332b5ca933f/Grounding%20DINO/GroundingDINO_with_Segment_Anything.ipynb
import cv2
import numpy as np
import numpy.typing as npt
def mask_to_polygon(mask:... | 51 | 1,704 |
InvokeAI | invokeai/backend/image_util/mediapipe_face/__init__.py | .py | # Adapted from https://github.com/huggingface/controlnet_aux
from PIL import Image
from invokeai.backend.image_util.mediapipe_face.mediapipe_face_common import generate_annotation
from invokeai.backend.image_util.util import np_to_pil, pil_to_np
def detect_faces(image: Image.Image, max_faces: int = 1, min_confidenc... | 16 | 585 |
InvokeAI | invokeai/backend/image_util/mediapipe_face/mediapipe_face_common.py | .py | from typing import Mapping
import mediapipe as mp
import numpy
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_face_detection = mp.solutions.face_detection # Only for counting faces.
mp_face_mesh = mp.solutions.face_mesh
mp_face_connections = mp.solutions.face_mesh_connecti... | 150 | 6,665 |
InvokeAI | invokeai/backend/image_util/normal_bae/__init__.py | .py | # Adapted from https://github.com/huggingface/controlnet_aux
import pathlib
import types
import cv2
import huggingface_hub
import numpy as np
import torch
import torchvision.transforms as transforms
from einops import rearrange
from PIL import Image
from invokeai.backend.image_util.normal_bae.nets.NNET import NNET
f... | 95 | 3,008 |
InvokeAI | invokeai/backend/image_util/normal_bae/nets/NNET.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .submodules.encoder import Encoder
from .submodules.decoder import Decoder
class NNET(nn.Module):
def __init__(self, args):
super(NNET, self).__init__()
self.encoder = Encoder()
self.decoder = Decoder(args)
def g... | 22 | 597 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.