text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
class FrozenDict(OrderedDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key, value in self.items():
setattr(self, key, value)
self.__frozen = True
def __delitem__(self, *args, **kwargs):
raise Exception(f"You cannot use ``__delitem... | 0 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
def __setitem__(self, name, value):
if hasattr(self, "__frozen") and self.__frozen:
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
super().__setitem__(name, value) | 0 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
class ConfigMixin:
r"""
Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
saving classes that inherit from [`ConfigMixin`]. | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Class attributes:
- **config_name** (`str`) -- A filename under which the config should stored when calling
[`~ConfigMixin.save_config`] (should be overridden by parent class).
- **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
def register_to_config(self, **kwargs):
if self.config_name is None:
raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
# Special case for `kwargs` used in deprecation warning added to schedulers
# TODO: remove this when we remove the... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
def __getattr__(self, name: str) -> Any:
"""The only reason we overwrite `getattr` here is to gracefully deprecate accessing
config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
This function is mostly copied from PyTorch's __getattr__ overwrite:
https://py... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
"""
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Args:
save_directory (`str` or `os.PathLike`):
Directory where the configuration JSON file is saved (will be created if it does not exist).
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or not to push your model to the Hugging Face Hub after savin... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
# If we save using the predefined names, we can load using `from_config`
output_config_file = os.path.join(save_directory, self.config_name)
self.to_json_file(output_config_file)
logger.info(f"Configuration saved in {output_config_file}")
if push_to_hub:
commit_message = kw... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
@classmethod
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
r"""
Instantiate a Python class from a config dictionary.
Parameters:
config (`Dict[str, Any]`):
A config dictionary from which the Python c... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Returns:
[`ModelMixin`] or [`SchedulerMixin`]:
A model or scheduler object instantiated from a config dictionary.
Examples:
```python
>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
>>> # Download scheduler from huggingface.co and cach... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
if config is None:
raise ValueError("Please make sure to provide a config as the first positional argument.")
# ======> | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
if not isinstance(config, dict):
deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
if "Scheduler" in cls.__name__:
deprecation_message += (
f"If you were trying to load a scheduler, please use {cls}.from_pretrai... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs) | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
# Allow dtype to be specified on initialization
if "dtype" in unused_kwargs:
init_dict["dtype"] = unused_kwargs.pop("dtype")
# add possible deprecated kwargs
for deprecated_kwarg in cls._depreca... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
if return_unused_kwargs:
return (model, unused_kwargs)
else:
return model
@classmethod
def get_config_dict(cls, *args, **kwargs):
deprecation_message = (
f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will b... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
the Hub.
- A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
[`~ConfigMixin.save_config`]. | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
cache_dir (`Union[str, os.PathLike]`, *optional*):
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force the (re-)dow... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Whether to only load local model weights and configuration files or not. If set to `True`, the model
won't be downloaded from the Hub.
token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Whether the `commit_hash` of the loaded configuration are returned. | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Returns:
`dict`:
A dictionary of all the parameters stored in a JSON configuration file.
"""
cache_dir = kwargs.pop("cache_dir", None)
local_dir = kwargs.pop("local_dir", None)
local_dir_use_symlinks = kwargs.pop("local_dir_use_symlinks", "auto")
forc... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
if cls.config_name is None:
raise ValueError(
"`self.config_name` is not defined. Note that one should not load a config from "
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
)
# Custom path for now
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
):
config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
elif os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
# Load from a PyTorc... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
local_files_only=local_files_only,
token=token,
user_agent=user_agent,
subfolder=subfolder,
revision=revision,
local_dir=local_dir,
local_dir_use_symlinks=local_dir_use_symlinks,
)
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
" this model name. Check the model page at"
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
)
except EntryNotFoundError:
raise EnvironmentError(
f"{pretrained_model_name_or_path} does not appear to ... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
" run the library in offline mode at"
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
)
except EnvironmentError:
r... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
commit_hash = extract_commit_hash(config_file)
except (json.JSONDecodeError, UnicodeDecodeError):
raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
if not (return_unused_kwargs or return_commit_hash):
return config_dict
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
# 0. Copy origin config dict
original_dict = dict(config_dict.items())
# 1. Retrieve expected config attributes from __init__ signature
expected_keys = cls._get_init_keys(cls)
expected_keys.remove("self")
# remove general kwargs if present in dict
if "kwargs" in expected... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
if cls.has_compatibles:
compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
else:
compatible_classes = []
expected_keys_comp_cls = set()
for c in compatible_classes:
expected_keys_c = cls._get_init_keys(c)
ex... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
# remove attributes from orig class that cannot be expected
orig_cls_name = config_dict.pop("_class_name", cls.__name__)
if (
isinstance(orig_cls_name, str)
and orig_cls_name != cls.__name__
and hasattr(diffusers_library, orig_cls_name)
):
orig_cls... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
# remove quantization_config
config_dict = {k: v for k, v in config_dict.items() if k != "quantization_config"}
# 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
init_dict = {}
for key in expected_keys:
# if config param is passed ... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
# 4. Give nice warning if unexpected values have been passed
if len(config_dict) > 0:
logger.warning(
f"The config attributes {config_dict} were passed to {cls.__name__}, "
"but are not expected and will be ignored. Please verify your "
f"{cls.config_n... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
return init_dict, unused_kwargs, hidden_config_dict
@classmethod
def _dict_from_json_file(
cls, json_file: Union[str, os.PathLike], dduf_entries: Optional[Dict[str, DDUFEntry]] = None
):
if dduf_entries:
text = dduf_entries[json_file].read_text()
else:
with o... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
Returns:
`str`:
String containing all the attributes that make up the configuration instance in JSON format.
"""
config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
config_dict["_class_name"] = self.__class__.__name__
config_dict["_dif... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
# Don't save "_ignore_files" or "_use_default_values"
config_dict.pop("_ignore_files", None)
config_dict.pop("_use_default_values", None)
# pop the `_pre_quantization_dtype` as torch.dtypes are not serializable.
... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
@classmethod
def _get_config_file_from_dduf(cls, pretrained_model_name_or_path: str, dduf_entries: Dict[str, DDUFEntry]):
# paths inside a DDUF file must always be "/"
config_file = (
cls.config_name
if pretrained_model_name_or_path == ""
else "/".join([pretrained... | 1 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
class LegacyConfigMixin(ConfigMixin):
r"""
A subclass of `ConfigMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
pipeline-specific classes (like `DiTTransformer2DModel`).
"""
@classmethod
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = Non... | 2 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/configuration_utils.py |
class VaeImageProcessor(ConfigMixin):
"""
Image processor for VAE. | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
`height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
vae_scale_factor (`int... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
Whether to convert the images to grayscale format.
""" | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
config_name = CONFIG_NAME
@register_to_config
def __init__(
self,
do_resize: bool = True,
vae_scale_factor: int = 8,
vae_latent_channels: int = 4,
resample: str = "lanczos",
do_normalize: bool = True,
do_binarize: bool = False,
do_convert_rgb: boo... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
images (`np.ndarray`):
The image array to convert to PIL format.
Returns:
`List[PIL.Image.Image]`:
A list of PIL images.
"""
if images.ndim == 3:
images = images[None, ...]
images = (images * 255).round().astype("... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`np.ndarray`:
A NumPy array representation of the images.
"""
if not isinstance(images, list):
images = [images]
images = [np.array(image).astype(np.float32) / 255.0 for image in images]
images = np.stack(images, axis=0)
return im... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
images (`torch.Tensor`):
The PyTorch tensor to convert to NumPy format.
Returns:
`np.ndarray`:
A NumPy array representation of the images.
"""
images = images.cpu().permute(0, 2, 3, 1).float().numpy()
return images
@stat... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
images (`np.ndarray` or `torch.Tensor`):
The image array to denormalize.
Returns:
`np.ndarray` or `torch.Tensor`:
The denormalized image array.
"""
return (images * 0.5 + 0.5).clamp(0, 1)
@staticmethod
def convert_to_rgb(ima... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`PIL.Image.Image`:
The image converted to grayscale.
"""
image = image.convert("L")
return image
@staticmethod
def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
r"""
Applies Gaussian blur to an image.
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
@staticmethod
def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
r"""
Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect
ratio of the original image; for example, if user drew mask in a 128x32 region, an... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# 1. find a rectangular region that contains all masked ares in an image
h, w = mask.shape
crop_left = 0
for i in range(w):
if not (mask[:, i] == 0).all():
break
crop_left += 1
crop_right = 0
for i in reversed(range(w)):
if not... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# 3. expands crop region to match the aspect ratio of the image to be processed
ratio_crop_region = (x2 - x1) / (y2 - y1)
ratio_processing = width / height | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if ratio_crop_region > ratio_processing:
desired_height = (x2 - x1) / ratio_processing
desired_height_diff = int(desired_height - (y2 - y1))
y1 -= desired_height_diff // 2
y2 += desired_height_diff - desired_height_diff // 2
if y2 >= mask_image.height:
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
x1 -= x1
if x2 >= mask_image.width:
x2 = mask_image.width | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
return x1, y1, x2, y2
def _resize_and_fill(
self,
image: PIL.Image.Image,
width: int,
height: int,
) -> PIL.Image.Image:
r"""
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
the image within the... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if ratio < src_ratio:
fill_height = height // 2 - src_h // 2
if fill_height > 0:
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
res.paste(
resized.resize((width, fill_height), box=(0, resized.height, width, re... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
def _resize_and_crop(
self,
image: PIL.Image.Image,
width: int,
height: int,
) -> PIL.Image.Image:
r"""
Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
the image within the dimensions, cropping the e... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
return res
def resize(
self,
image: Union[PIL.Image.Image, np.ndarray, torch.Tens... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
The image input, can be a PIL image, numpy array or pytorch tensor.
height (`int`):
The height to resize to.
width (`int`):
The width to resize to.
resize_mode... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
the image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
supported for PIL image input. | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
The resized image.
"""
if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
if isinstance(im... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
elif isinstance(image, torch.Tensor):
image = torch.nn.functional.interpolate(
image,
size=(height, width),
)
elif isinstance(image, np.ndarray):
image = self.numpy_to_pt(image)
image = torch.nn.functional.interpolate(
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
def _denormalize_conditionally(
self, images: torch.Tensor, do_denormalize: Optional[List[bool]] = None
) -> torch.Tensor:
r"""
Denormalize a batch of images based on a condition list.
Args:
images (`torch.Tensor`):
The input image tensor.
do_... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
def get_default_height_width(
self,
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
height: Optional[int] = None,
width: Optional[int] = None,
) -> Tuple[int, int]:
r"""
Returns the height and width of the image, downscaled to the next integer multiple of `va... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
The image input, which can be a PIL image, NumPy array, or PyTorch tensor. If it is a NumPy array, it
should have shape `[batch, height, width]` or `[batch, height, width, channels]`. If it is a PyTorch
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if height is None:
if isinstance(image, PIL.Image.Image):
height = image.height
elif isinstance(image, torch.Tensor):
height = image.shape[2]
else:
height = image.shape[1]
if width is None:
if isinstance(image, PIL.... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
def preprocess(
self,
image: PipelineImageInput,
height: Optional[int] = None,
width: Optional[int] = None,
resize_mode: str = "default", # "default", "fill", "crop"
crops_coords: Optional[Tuple[int, int, int, int]] = None,
) -> torch.Tensor:
"""
Prep... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
image (`PipelineImageInput`):
The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
supported formats.
height (`int`, *optional*):
The height in preprocessed image. If `None`, will use the `get_d... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
center the image within the dimensions, filling empty with data from image. If `crop`, will resize the
image to fit within the specified width and height, maintaining the aspect ratio, and then center the
image within the dimensions, cropping the excess. Note that resize_mode `fill` and ... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`torch.Tensor`:
The preprocessed image.
"""
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor) | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
if isinstance(image, torch.Tensor):
# if image is a pytorch tensor... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# 2. height x width x channel: insert batch dimension on first position
if image.shape[-1] == 1:
image = np.expand_dims(image, axis=0)
else:
image = np.expand_dims(image, axis=-1) | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if isinstance(image, list) and isinstance(image[0], np.ndarray) and image[0].ndim == 4:
warnings.warn(
"Passing `image` as a list of 4d np.ndarray is deprecated."
"Please concatenate the list along the batch dimension and pass it as a single 4d np.ndarray",
Fu... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if not is_valid_image_imagelist(image):
raise ValueError(
f"Input is in incorrect format. Currently, we only support {', '.join(str(x) for x in supported_formats)}"
)
if not isinstance(image, list):
image = [image]
if isinstance(image[0], PIL.Image.Im... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
elif isinstance(image[0], np.ndarray):
image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
image = self.numpy_to_pt(image)
height, width = self.get_default_height_width(image, height, width)
if self.config.do_resize:
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# expected range [0,1], normalize to [-1,1]
do_normalize = self.config.do_normalize
if do_normalize and image.min() < 0:
warnings.warn(
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
image (`torch.Tensor`):
The image input, should be a pytorch tensor with shape `B x C x H x W`.
output_type (`str`, *optional*, defaults to `pil`):
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
do_denormalize (`List[boo... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
The postprocessed image.
"""
if not isinstance(image, torch.Tensor):
raise ValueError(
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if output_type == "np":
return image
if output_type == "pil":
return self.numpy_to_pil(image)
def apply_overlay(
self,
mask: PIL.Image.Image,
init_image: PIL.Image.Image,
image: PIL.Image.Image,
crop_coords: Optional[Tuple[int, int, int, int]... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`PIL.Image.Image`:
The final image with the overlay applied.
"""
width, height = init_image.width, init_image.height
init_image_masked = PIL.Image.new("RGBa", (width, height))
init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=... | 3 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
class VaeImageProcessorLDM3D(VaeImageProcessor):
"""
Image processor for VAE LDM3D.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
vae_scale_factor (`int`, *optional*, defa... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
@staticmethod
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
r"""
Convert a NumPy image or a batch of images to a list of PIL images.
Args:
images (`np.ndarray`):
The input NumPy array of images, which can be a single image or a batch.
Re... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
@staticmethod
def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
r"""
Convert a PIL image or a list of PIL images to NumPy arrays.
Args:
images (`Union[List[PIL.Image.Image], PIL.Image.Image]`):
The input image or list of... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`Union[np.ndarray, torch.Tensor]`:
The corresponding depth map.
"""
return image[:, :, 1] * 2**8 + image[:, :, 2]
def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
r"""
Convert a NumPy depth image or a batch of images to a li... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`List[PIL.Image.Image]`:
A list of PIL images converted from the input NumPy depth images.
"""
if images.ndim == 3:
images = images[None, ...]
images_depth = images[:, :, :, 3:]
if images.shape[-1] == 6:
images_depth = (images_... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
def postprocess(
self,
image: torch.Tensor,
output_type: str = "pil",
do_denormalize: Optional[List[bool]] = None,
) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
"""
Postprocess the image output from tensor to `output_type`.
Args:
image (`... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
The postprocessed image.
"""
if not isinstance(image, torch.Tensor):
raise ValueError(
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if output_type == "np":
if image.shape[-1] == 6:
image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
else:
image_depth = image[:, :, :, 3:]
return image[:, :, :, :3], image_depth
if output_type == "pil":
... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
rgb (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
The RGB input image, which can be a single image or a batch.
depth (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
The depth input image, which can be a single image or a batch.
heig... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Returns:
`Tuple[torch.Tensor, torch.Tensor]`:
A tuple containing the processed RGB and depth images as PyTorch tensors.
"""
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array ... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
if isinstance(rgb[0], PIL.Image.Image):
if self.config.do_convert_rgb:
raise Exception("This is not yet supported")
# rgb = [self.convert_to_rgb(i) for i in rgb]
# depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
if ... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
elif isinstance(rgb[0], np.ndarray):
rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
rgb = self.numpy_to_pt(rgb)
height, width = self.get_default_height_width(rgb, height, width)
if self.config.do_resize:
rgb = self.resize(... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# height, width = self.get_default_height_width(rgb, height, width)
# if self.config.do_resize:
# rgb = self.resize(rgb, height, width)
# depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
# if self.config.do_convert_grayscale and... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# height, width = self.get_default_height_width(depth, height, width)
# if self.config.do_resize:
# depth = self.resize(depth, height, width)
# expected range [0,1], normalize to [-1,1]
do_normalize = self.config.do_normalize
if rgb.min() < 0 and do_normalize:
... | 4 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
class IPAdapterMaskProcessor(VaeImageProcessor):
"""
Image processor for IP Adapter image masks.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
vae_scale_factor (`int`, *op... | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
@register_to_config
def __init__(
self,
do_resize: bool = True,
vae_scale_factor: int = 8,
resample: str = "lanczos",
do_normalize: bool = False,
do_binarize: bool = True,
do_convert_grayscale: bool = True,
):
super().__init__(
do_resiz... | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
Args:
mask (`torch.Tensor`):
The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
batch_size (`int`):
The batch size.
num_queries (`int`):
The number of queries.
value_embed_dim (`int`):
... | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1) | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
downsampled_area = mask_h * mask_w
# If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
# Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
if downsampled_area < num_queries:
warnings.warn(
"The aspect ra... | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
UserWarning,
)
mask_downsample = mask_downsample[:, :num_queries] | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
# Repeat last dimension to match SDPA output shape
mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
1, 1, value_embed_dim
)
return mask_downsample | 5 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
class PixArtImageProcessor(VaeImageProcessor):
"""
Image processor for PixArt image resize and crop. | 6 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4