




'''simple docstring'''







import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class   _snake_case( UpperCAmelCase					,   unittest.TestCase			):
 __snake_case:       Any									=				PaintByExamplePipeline
 __snake_case:       int									=				IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
 __snake_case:       Union[str, Any]									=				IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 __snake_case:       List[str]									=				frozenset([]			)  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess






 def 	_UpperCamelCase   (self					:     int						)					->      str:






    """simple docstring"""


    torch.manual_seed(0						)
    A__         =    UNetaDConditionModel(
        block_out_channels=(32, 64)						,		layers_per_block=2						,		sample_size=32						,		in_channels=9						,		out_channels=4						,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')						,		up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')						,		cross_attention_dim=32						,		)
    A__         =    PNDMScheduler(skip_prk_steps=a						)
    torch.manual_seed(0						)
    A__         =    AutoencoderKL(
        block_out_channels=[32, 64]						,		in_channels=3						,		out_channels=3						,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']						,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']						,		latent_channels=4						,		)
    torch.manual_seed(0						)
    A__         =    CLIPVisionConfig(
        hidden_size=32						,		projection_dim=32						,		intermediate_size=37						,		layer_norm_eps=1e-05						,		num_attention_heads=4						,		num_hidden_layers=5						,		image_size=32						,		patch_size=4						,		)
    A__         =    PaintByExampleImageEncoder(a						,		proj_size=32						)
    A__         =    CLIPImageProcessor(crop_size=32						,		size=32						)

    A__         =    {
        'unet': unet,
        'scheduler': scheduler,
        'vae': vae,
        'image_encoder': image_encoder,
        'safety_checker': None,
        'feature_extractor': feature_extractor,
    }
    return components






 def 	_UpperCamelCase   (self					:     List[Any]						,		a					:     Tuple						)					->      Optional[Any]:






    """simple docstring"""


    A__         =    np.array(image.convert('RGB'						)						)
    A__         =    image[None].transpose(0						,		3						,		1						,		2						)
    A__         =    torch.from_numpy(a						).to(dtype=torch.floataa						) / 127.5 - 1.0
    return image






 def 	_UpperCamelCase   (self					:     Any						,		a					:     Dict="cpu"						,		a					:     Optional[Any]=0						)					->      Any:






    """simple docstring"""


    A__         =    floats_tensor((1, 3, 32, 32)						,		rng=random.Random(a						)						).to(a						)
    A__         =    image.cpu().permute(0						,		2						,		3						,		1						)[0]
    A__         =    Image.fromarray(np.uinta(a						)						).convert('RGB'						).resize((64, 64)						)
    A__         =    Image.fromarray(np.uinta(image + 4						)						).convert('RGB'						).resize((64, 64)						)
    A__         =    Image.fromarray(np.uinta(a						)						).convert('RGB'						).resize((32, 32)						)

    if str(a						).startswith('mps'						):
       A__         =    torch.manual_seed(a						)
    else:
       A__         =    torch.Generator(device=a						).manual_seed(a						)
    A__         =    {
        'example_image': example_image,
        'image': init_image,
        'mask_image': mask_image,
        'generator': generator,
        'num_inference_steps': 2,
        'guidance_scale': 6.0,
        'output_type': 'numpy',
    }
    return inputs






 def 	_UpperCamelCase   (self					:     Tuple						)					->      int:






    """simple docstring"""


    A__         =    self.get_dummy_components()

    # make sure here that pndm scheduler skips prk
    A__         =    PaintByExamplePipeline(**a						)
    A__         =    pipe.to('cpu'						)
    pipe.set_progress_bar_config(disable=a						)

    A__         =    self.get_dummy_inputs()
    A__         =    pipe(**a						)
    A__         =    output.images

    A__         =    image[0, -3:, -3:, -1]

    assert image.shape == (1, 64, 64, 3)
    A__         =    np.array([0.4686, 0.5687, 0.4007, 0.5218, 0.5741, 0.4482, 0.4940, 0.4629, 0.4503]						)

    assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2






 def 	_UpperCamelCase   (self					:     List[Any]						)					->      Dict:






    """simple docstring"""


    A__         =    'cpu'
    A__         =    self.get_dummy_inputs()
    inputs.pop('mask_image'						)
    A__         =    self.convert_to_pt(inputs.pop('image'						)						)
    A__         =    image.clamp(0						,		1						) / 2

    # make sure here that pndm scheduler skips prk
    A__         =    PaintByExamplePipeline(**self.get_dummy_components()						)
    A__         =    pipe.to(a						)
    pipe.set_progress_bar_config(disable=a						)

    A__         =    pipe(image=a						,		mask_image=mask_image[:, 0]						,		**a						)
    A__         =    output.images

    A__         =    image.cpu().permute(0						,		2						,		3						,		1						)[0]
    A__         =    mask_image.cpu().permute(0						,		2						,		3						,		1						)[0]

    A__         =    Image.fromarray(np.uinta(a						)						).convert('RGB'						)
    A__         =    Image.fromarray(np.uinta(a						)						).convert('RGB'						)

    A__         =    pipe(**self.get_dummy_inputs()						)
    A__         =    output.images

    assert out_a.shape == (1, 64, 64, 3)
    assert np.abs(out_a.flatten() - out_a.flatten()						).max() < 5e-2






 def 	_UpperCamelCase   (self					:     Optional[int]						)					->      Optional[int]:






    """simple docstring"""


    super().test_inference_batch_single_identical(expected_max_diff=3e-3						)




@slow
@require_torch_gpu
class   _snake_case( unittest.TestCase			):






 def 	_UpperCamelCase   (self					:     Optional[int]						)					->      Tuple:






    """simple docstring"""


    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()






 def 	_UpperCamelCase   (self					:     List[Any]						)					->      Optional[int]:






    """simple docstring"""


    A__         =    load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/paint_by_example/dog_in_bucket.png'						)
    A__         =    load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/paint_by_example/mask.png'						)
    A__         =    load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/paint_by_example/panda.jpg'						)

    A__         =    PaintByExamplePipeline.from_pretrained('Fantasy-Studio/Paint-by-Example'						)
    A__         =    pipe.to(a						)
    pipe.set_progress_bar_config(disable=a						)

    A__         =    torch.manual_seed(3_21						)
    A__         =    pipe(
        image=a						,		mask_image=a						,		example_image=a						,		generator=a						,		guidance_scale=5.0						,		num_inference_steps=50						,		output_type='np'						,		)

    A__         =    output.images

    A__         =    image[0, -3:, -3:, -1]

    assert image.shape == (1, 5_12, 5_12, 3)
    A__         =    np.array([0.4834, 0.4811, 0.4874, 0.5122, 0.5081, 0.5144, 0.5291, 0.5290, 0.5374]						)

    assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2








'''simple docstring'''







import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


lowerCAmelCase_    	=							logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
lowerCAmelCase_    	=							direct_transformers_import(Path(__file__).parent)


lowerCAmelCase_    	=							{
    '''AutoTokenizer''': '''PreTrainedTokenizerBase''',
    '''AutoFeatureExtractor''': '''FeatureExtractionMixin''',
    '''AutoImageProcessor''': '''ImageProcessingMixin''',
}

class   _snake_case( UpperCAmelCase			):
 __snake_case:       str									=				['''feature_extractor''', '''tokenizer''']
 # Names need to be attr_class for attr in attributes
 __snake_case:       Optional[Any]									=				None
 __snake_case:       List[str]									=				None
 __snake_case:       Any									=				None






 def __init__(self					:     List[Any]						,		*a					:     Union[str, Any]						,		**a					:     Optional[int]						)					->      Any:






    """simple docstring"""


    for key in kwargs:
       if key not in self.attributes:
          raise TypeError(f"""Unexpected keyword argument {key}."""						)
    for arg, attribute_name in zip(a						,		self.attributes						):
       if attribute_name in kwargs:
          raise TypeError(f"""Got multiple values for argument {attribute_name}."""						)
       else:
          A__         =    arg

    if len(a						) != len(self.attributes						):
       raise ValueError(
           f"""This processor requires {len(self.attributes						)} arguments: {", ".join(self.attributes						)}. Got """
           f"""{len(a						)} arguments instead."""						)

    # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
    for attribute_name, arg in kwargs.items():
       A__         =    getattr(self						,		f"""{attribute_name}_class"""						)
       # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
       A__         =    AUTO_TO_BASE_CLASS_MAPPING.get(a						,		a						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) for n in class_name if n is not None						)
       else:
          A__         =    getattr(a						,		a						)

       if not isinstance(a						,		a						):
          raise ValueError(
              f"""Received a {type(a						).__name__} for argument {attribute_name}, but a {class_name} was expected."""						)

       setattr(self						,		a						,		a						)






 def __repr__(self					:     Optional[int]						)					->      Any:






    """simple docstring"""


    A__         =    [f"""- {name}: {repr(getattr(self						,		a						)						)}""" for name in self.attributes]
    A__         =    '\n'.join(a						)
    return f"""{self.__class__.__name__}:\n{attributes_repr}"""






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     Tuple						,		a					:     bool = False						,		**a					:     int						)					->      List[str]:






    """simple docstring"""


    os.makedirs(a						,		exist_ok=a						)

    if push_to_hub:
       A__         =    kwargs.pop('commit_message'						,		a						)
       A__         =    kwargs.pop('repo_id'						,		save_directory.split(os.path.sep						)[-1]						)
       A__         =    self._create_repo(a						,		**a						)
       A__         =    self._get_files_timestamps(a						)
    # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
    # loaded from the Hub.
    if self._auto_class is not None:
       A__         =    [getattr(self						,		a						) for attribute_name in self.attributes]
       A__         =    [(a.init_kwargs if isinstance(a						,		a						) else a) for a in attrs]
       custom_object_save(self						,		a						,		config=a						)

    for attribute_name in self.attributes:
       A__         =    getattr(self						,		a						)
       # Include the processor class in the attribute config so this processor can then be reloaded with the
       # `AutoProcessor` API.
       if hasattr(a						,		'_set_processor_class'						):
          attribute._set_processor_class(self.__class__.__name__						)
       attribute.save_pretrained(a						)

    if self._auto_class is not None:
       # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
       for attribute_name in self.attributes:
          A__         =    getattr(self						,		a						)
          if isinstance(a						,		a						):
             del attribute.init_kwargs["auto_map"]

    if push_to_hub:
       self._upload_modified_files(
           a						,		a						,		a						,		commit_message=a						,		token=kwargs.get('use_auth_token'						)						,		)






 @classmethod
 def 	_UpperCamelCase   (cls					:     int						,		a					:     Union[str, os.PathLike]						,		a					:     Optional[Union[str, os.PathLike]] = None						,		a					:     bool = False						,		a					:     bool = False						,		a					:     Optional[Union[str, bool]] = None						,		a					:     str = "main"						,		**a					:     Union[str, Any]						,		)					->      Optional[Any]:






    """simple docstring"""


    A__         =    cache_dir
    A__         =    force_download
    A__         =    local_files_only
    A__         =    revision

    A__         =    kwargs.pop('use_auth_token'						,		a						)
    if use_auth_token is not None:
       warnings.warn(
           'The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.'						,		a						)
       if token is not None:
          raise ValueError(
              '`token` and `use_auth_token` are both specified. Please set only the argument `token`.'						)
       A__         =    use_auth_token

    if token is not None:
       # change to `token` in a follow-up PR
       A__         =    token

    A__         =    cls._get_arguments_from_pretrained(a						,		**a						)
    return cls(*a						)






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[int]						,		a					:     Union[str, Any]="AutoProcessor"						)					->      Any:






    """simple docstring"""


    if not isinstance(a						,		a						):
       A__         =    auto_class.__name__

    import transformers.models.auto as auto_module

    if not hasattr(a						,		a						):
       raise ValueError(f"""{auto_class} is not a valid auto class."""						)

    A__         =    auto_class






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[Any]						,		a					:     Optional[Any]						,		**a					:     Tuple						)					->      int:






    """simple docstring"""


    A__         =    []
    for attribute_name in cls.attributes:
       A__         =    getattr(cls						,		f"""{attribute_name}_class"""						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) if n is not None else None for n in class_name						)
          A__         =    kwargs.get('use_fast'						,		a						)
          if use_fast and classes[1] is not None:
             A__         =    classes[1]
          else:
             A__         =    classes[0]
       else:
          A__         =    getattr(a						,		a						)

       args.append(attribute_class.from_pretrained(a						,		**a						)						)
    return args






 @property
 def 	_UpperCamelCase   (self					:     str						)					->      List[str]:






    """simple docstring"""


    A__         =    getattr(self						,		self.attributes[0]						)
    return getattr(a						,		'model_input_names'						,		a						)




lowerCAmelCase_    	=							copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
    lowerCAmelCase_    	=							ProcessorMixin.push_to_hub.__doc__.format(
        object='''processor''', object_class='''AutoProcessor''', object_files='''processor files'''
    )


