




'''simple docstring'''







import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
   import numpy as np
   import torch

if is_vision_available():
   from PIL import Image





def 		snake_case_				(_a      :				int       ,  _a      :				Optional[Any]=False       ,  _a      :				Any=False       ,  _a      :				Union[str, Any]=False	):
    assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

    UpperCAmelCase     			=						[]
    for i in range(image_processor_tester.batch_size	):
        if equal_resolution:
            UpperCAmelCase     			=						image_processor_tester.max_resolution
        else:
            # To avoid getting image width/height 0
            UpperCAmelCase     			=						image_processor_tester.min_resolution
            if getattr(_a       ,  '''size_divisor'''       ,  _a	):
                # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
                UpperCAmelCase     			=						max(image_processor_tester.size_divisor       ,  _a	)
            UpperCAmelCase     			=						np.random.choice(np.arange(_a       ,  image_processor_tester.max_resolution	)       ,  2	)
        image_inputs.append(
            np.random.randint(2_5_5       ,  size=(image_processor_tester.num_channels, width, height)       ,  dtype=np.uinta	)	)

    if not numpify and not torchify:
        # PIL expects the channel dimension as last dimension
        UpperCAmelCase     			=						[Image.fromarray(np.moveaxis(_a       ,  0       ,  -1	)	) for image in image_inputs]

    if torchify:
        UpperCAmelCase     			=						[torch.from_numpy(_a	) for image in image_inputs]

    return image_inputs





def 		snake_case_				(_a      :				Dict       ,  _a      :				Dict=1_0       ,  _a      :				str=1_0       ,  _a      :				Optional[int]=False       ,  _a      :				Union[str, Any]=False	):
    UpperCAmelCase     			=						[]
    for i in range(image_processor_tester.num_frames	):
        video.append(np.random.randint(2_5_5       ,  size=(image_processor_tester.num_channels, width, height)       ,  dtype=np.uinta	)	)

    if not numpify and not torchify:
        # PIL expects the channel dimension as last dimension
        UpperCAmelCase     			=						[Image.fromarray(np.moveaxis(_a       ,  0       ,  -1	)	) for frame in video]

    if torchify:
        UpperCAmelCase     			=						[torch.from_numpy(_a	) for frame in video]

    return video





def 		snake_case_				(_a      :				List[str]       ,  _a      :				Optional[Any]=False       ,  _a      :				Optional[int]=False       ,  _a      :				Tuple=False	):
    assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

    UpperCAmelCase     			=						[]
    for i in range(image_processor_tester.batch_size	):
        if equal_resolution:
            UpperCAmelCase     			=						image_processor_tester.max_resolution
        else:
            UpperCAmelCase     			=						np.random.choice(
                np.arange(image_processor_tester.min_resolution       ,  image_processor_tester.max_resolution	)       ,  2	)
            UpperCAmelCase     			=						prepare_video(
                image_processor_tester=_a       ,  width=_a       ,  height=_a       ,  numpify=_a       ,  torchify=_a       ,  )
        video_inputs.append(_a	)

    return video_inputs







class      _a    :
       __a							:	Tuple  							=   None
       def        A (      self		:      Any							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.image_processing_class(**self.image_processor_dict							)
           UpperCAmelCase     			=						json.loads(image_processor.to_json_string()							)
           for key, value in self.image_processor_dict.items():
               self.assertEqual(obj[key]  ,							_SCREAMING_SNAKE_CASE							)
       def        A (      self		:      Dict							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.image_processing_class(**self.image_processor_dict							)

           with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase     			=						os.path.join(_SCREAMING_SNAKE_CASE  ,							'''image_processor.json'''							)
               image_processor_first.to_json_file(_SCREAMING_SNAKE_CASE							)
               UpperCAmelCase     			=						self.image_processing_class.from_json_file(_SCREAMING_SNAKE_CASE							)

           self.assertEqual(image_processor_second.to_dict()  ,							image_processor_first.to_dict()							)
       def        A (      self		:      Optional[int]							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.image_processing_class(**self.image_processor_dict							)

           with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase     			=						image_processor_first.save_pretrained(_SCREAMING_SNAKE_CASE							)[0]
               check_json_file_has_correct_format(_SCREAMING_SNAKE_CASE							)
               UpperCAmelCase     			=						self.image_processing_class.from_pretrained(_SCREAMING_SNAKE_CASE							)

           self.assertEqual(image_processor_second.to_dict()  ,							image_processor_first.to_dict()							)
       def        A (      self		:      Optional[int]							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.image_processing_class()
           self.assertIsNotNone(_SCREAMING_SNAKE_CASE							)







       @require_torch
       @require_vision
       def        A (      self		:      Optional[int]							):



           '''simple docstring'''

           if self.test_cast_dtype is not None:
               # Initialize image_processor
               UpperCAmelCase     			=						self.image_processing_class(**self.image_processor_dict							)

               # create random PyTorch tensors
               UpperCAmelCase     			=						prepare_image_inputs(self.image_processor_tester  ,							equal_resolution=_SCREAMING_SNAKE_CASE  ,							torchify=_SCREAMING_SNAKE_CASE							)

               UpperCAmelCase     			=						image_processor(_SCREAMING_SNAKE_CASE  ,							return_tensors='''pt'''							)
               # for layoutLM compatiblity
               self.assertEqual(encoding.pixel_values.device  ,							torch.device('''cpu'''							)							)
               self.assertEqual(encoding.pixel_values.dtype  ,							torch.floataa							)

               UpperCAmelCase     			=						image_processor(_SCREAMING_SNAKE_CASE  ,							return_tensors='''pt'''							).to(torch.floataa							)
               self.assertEqual(encoding.pixel_values.device  ,							torch.device('''cpu'''							)							)
               self.assertEqual(encoding.pixel_values.dtype  ,							torch.floataa							)

               UpperCAmelCase     			=						image_processor(_SCREAMING_SNAKE_CASE  ,							return_tensors='''pt'''							).to('''cpu'''  ,							torch.bfloataa							)
               self.assertEqual(encoding.pixel_values.device  ,							torch.device('''cpu'''							)							)
               self.assertEqual(encoding.pixel_values.dtype  ,							torch.bfloataa							)

               with self.assertRaises(_SCREAMING_SNAKE_CASE							):
                   UpperCAmelCase     			=						image_processor(_SCREAMING_SNAKE_CASE  ,							return_tensors='''pt'''							).to(torch.bfloataa  ,							'''cpu'''							)

               # Try with text + image feature
               UpperCAmelCase     			=						image_processor(_SCREAMING_SNAKE_CASE  ,							return_tensors='''pt'''							)
               encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]							)}							)
               UpperCAmelCase     			=						encoding.to(torch.floataa							)

               self.assertEqual(encoding.pixel_values.device  ,							torch.device('''cpu'''							)							)
               self.assertEqual(encoding.pixel_values.dtype  ,							torch.floataa							)
               self.assertEqual(encoding.input_ids.dtype  ,							torch.long							)








import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
		from .testing_utils import (
		    floats_tensor,
		    load_hf_numpy,
		    load_image,
		    load_numpy,
		    load_pt,
		    nightly,
		    parse_flag_from_env,
		    print_tensor_test,
		    require_torch_a,
		    require_torch_gpu,
		    skip_mps,
		    slow,
		    torch_all_close,
		    torch_device,
		)
		from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


lowerCamelCase		=						get_logger(__name__)






def 	lowerCamelCase_       (			_a			):




		"""simple docstring"""






		if version.parse(_a			) < version.parse(_a			):
				if "dev" in min_version:
						lowerCAmelCase__  :     Tuple       	=   (
						    '''This example requires a source install from HuggingFace diffusers (see '''
						    '''`https://huggingface.co/docs/diffusers/installation#install-from-source`),'''
						)
				else:
						lowerCAmelCase__  :     Dict       	=   f'This example requires a minimum version of {min_version},'
				error_message += f' but the version found is {__version__}.\n'
				raise ImportError(_a			)




