from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import TFCvtForImageClassification, TFCvtModel
    from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.config_class(**self.inputs_dict)
        self.parent.assertTrue(hasattr(lowercase__      ,   'embed_dim'))
        self.parent.assertTrue(hasattr(lowercase__      ,   'num_heads'))






class     a_			:






 '''simple docstring'''






 def __init__(      self :  Any      ,   lowercase__ :  List[Any]      ,   lowercase__ :  List[Any]=13      ,   lowercase__ :  str=64      ,   lowercase__ :  Optional[int]=3      ,   lowercase__ :  int=[16, 48, 96]      ,   lowercase__ :  Optional[int]=[1, 3, 6]      ,   lowercase__ :  Optional[Any]=[1, 2, 10]      ,   lowercase__ :  List[Any]=[7, 3, 3]      ,   lowercase__ :  Any=[4, 2, 2]      ,   lowercase__ :  Tuple=[2, 1, 1]      ,   lowercase__ :  Optional[int]=[2, 2, 2]      ,   lowercase__ :  Optional[int]=[False, False, True]      ,   lowercase__ :  Tuple=[0.0, 0.0, 0.0]      ,   lowercase__ :  List[str]=0.02      ,   lowercase__ :  int=1e-12      ,   lowercase__ :  Dict=True      ,   lowercase__ :  List[Any]=True      ,   lowercase__ :  List[Any]=2      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = parent
        lowerCAmelCase__					     = batch_size
        lowerCAmelCase__					     = image_size
        lowerCAmelCase__					     = patch_sizes
        lowerCAmelCase__					     = patch_stride
        lowerCAmelCase__					     = patch_padding
        lowerCAmelCase__					     = is_training
        lowerCAmelCase__					     = use_labels
        lowerCAmelCase__					     = num_labels
        lowerCAmelCase__					     = num_channels
        lowerCAmelCase__					     = embed_dim
        lowerCAmelCase__					     = num_heads
        lowerCAmelCase__					     = stride_kv
        lowerCAmelCase__					     = depth
        lowerCAmelCase__					     = cls_token
        lowerCAmelCase__					     = attention_drop_rate
        lowerCAmelCase__					     = initializer_range
        lowerCAmelCase__					     = layer_norm_eps




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        lowerCAmelCase__					     = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

        lowerCAmelCase__					     = None
        if self.use_labels:
               # create a random int32 tensor of given shape
               lowerCAmelCase__					     = ids_tensor([self.batch_size]      ,   self.num_labels)

        lowerCAmelCase__					     = self.get_config()
        return config, pixel_values, labels




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        return CvtConfig(
            image_size=self.image_size      ,   num_labels=self.num_labels      ,   num_channels=self.num_channels      ,   embed_dim=self.embed_dim      ,   num_heads=self.num_heads      ,   patch_sizes=self.patch_sizes      ,   patch_padding=self.patch_padding      ,   patch_stride=self.patch_stride      ,   stride_kv=self.stride_kv      ,   depth=self.depth      ,   cls_token=self.cls_token      ,   attention_drop_rate=self.attention_drop_rate      ,   initializer_range=self.initializer_range      ,   )




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  int      ,   lowercase__ :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtModel(config=lowercase__)
        lowerCAmelCase__					     = model(lowercase__      ,   training=lowercase__)
        lowerCAmelCase__					     = (self.image_size, self.image_size)
        lowerCAmelCase__     , lowerCAmelCase__					     = image_size[0], image_size[1]
        for i in range(len(self.depth)):
               lowerCAmelCase__					     = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
               lowerCAmelCase__					     = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
        self.parent.assertEqual(result.last_hidden_state.shape      ,   (self.batch_size, self.embed_dim[-1], height, width))




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  str      ,   lowercase__ :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.num_labels
        lowerCAmelCase__					     = TFCvtForImageClassification(lowercase__)
        lowerCAmelCase__					     = model(lowercase__      ,   labels=lowercase__      ,   training=lowercase__)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels))




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.prepare_config_and_inputs()
        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = config_and_inputs
        lowerCAmelCase__					     = {'pixel_values': pixel_values}
        return config, inputs_dict






@require_tf
class     a_			(						SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
 UpperCAmelCase_     			= (
     {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
     if is_tf_available()
     else {}
 )
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtModelTester(self)
        lowerCAmelCase__					     = TFCvtConfigTester(self      ,   config_class=lowercase__      ,   has_text_modality=lowercase__      ,   hidden_size=37)




 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        self.config_tester.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()




 @unittest.skip(reason='Cvt does not output attentions')
 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Cvt does not use inputs_embeds')
 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Cvt does not support input and output embeddings')
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        pass




 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0      ,   reason='TF does not support backprop for grouped convolutions on CPU.'      ,   )
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        super().test_dataset_conversion()




 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0      ,   reason='TF does not support backprop for grouped convolutions on CPU.'      ,   )
 @slow
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        super().test_keras_fit()




 @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8')
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = tf.keras.mixed_precision.Policy('mixed_float16')
        tf.keras.mixed_precision.set_global_policy(lowercase__)
        super().test_keras_fit()
        tf.keras.mixed_precision.set_global_policy('float32')




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = inspect.signature(model.call)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               lowerCAmelCase__					     = [*signature.parameters.keys()]

               lowerCAmelCase__					     = ['pixel_values']
               self.assertListEqual(arg_names[:1]      ,   lowercase__)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        def check_hidden_states_output(lowercase__ :  str      ,   lowercase__ :  str      ,   lowercase__ :  Tuple):
               lowerCAmelCase__					     = model_class(lowercase__)

               lowerCAmelCase__					     = model(**self._prepare_for_class(lowercase__      ,   lowercase__))
               lowerCAmelCase__					     = outputs.hidden_states

               lowerCAmelCase__					     = len(self.model_tester.depth)
               self.assertEqual(len(lowercase__)      ,   lowercase__)

               # verify the first hidden states (first block)
               self.assertListEqual(
                   list(hidden_states[0].shape[-3:])      ,   [
                       self.model_tester.embed_dim[0],
                       self.model_tester.image_size // 4,
                       self.model_tester.image_size // 4,
                   ]      ,   )

        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = True
               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               lowerCAmelCase__					     = True

               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__)




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase__)




 @slow
 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowerCAmelCase__					     = TFCvtModel.from_pretrained(lowercase__)
               self.assertIsNotNone(lowercase__)






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image



@require_tf
@require_vision
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 @cached_property
 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])




 @slow
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(images=lowercase__      ,   return_tensors='tf')

        # forward pass
        lowerCAmelCase__					     = model(**lowercase__)

        # verify the logits
        lowerCAmelCase__					     = tf.TensorShape((1, 1_000))
        self.assertEqual(outputs.logits.shape      ,   lowercase__)

        lowerCAmelCase__					     = tf.constant([0.9_285, 0.9_015, -0.3_150])
        self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,   lowercase__      ,   atol=1e-4))

import argparse
import math
import os

import torch
from neural_compressor.utils.pytorch import load
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = argparse.ArgumentParser()
       parser.add_argument(
           '-m'     ,  '--pretrained_model_name_or_path'     ,  type=lowerCAmelCase__     ,  default=lowerCAmelCase__     ,  required=lowerCAmelCase__     ,  help='Path to pretrained model or model identifier from huggingface.co/models.'     ,  )
       parser.add_argument(
           '-c'     ,  '--caption'     ,  type=lowerCAmelCase__     ,  default='robotic cat with wings'     ,  help='Text used to generate images.'     ,  )
       parser.add_argument(
           '-n'     ,  '--images_num'     ,  type=lowerCAmelCase__     ,  default=4     ,  help='How much images to generate.'     ,  )
       parser.add_argument(
           '-s'     ,  '--seed'     ,  type=lowerCAmelCase__     ,  default=4_2     ,  help='Seed for random process.'     ,  )
       parser.add_argument(
           '-ci'     ,  '--cuda_id'     ,  type=lowerCAmelCase__     ,  default=0     ,  help='cuda_id.'     ,  )
       lowerCAmelCase__					     = parser.parse_args()
       return args






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ,  lowerCAmelCase__     ):
       if not len(lowerCAmelCase__     ) == rows * cols:
              raise ValueError('The specified number of rows and columns are not correct.'     )

       lowerCAmelCase__     , lowerCAmelCase__					     = imgs[0].size
       lowerCAmelCase__					     = Image.new('RGB'     ,  size=(cols * w, rows * h)     )
       lowerCAmelCase__     , lowerCAmelCase__					     = grid.size

       for i, img in enumerate(lowerCAmelCase__     ):
              grid.paste(lowerCAmelCase__     ,  box=(i % cols * w, i // cols * h)     )
       return grid






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__="robotic cat with wings"     ,  lowerCAmelCase__=7.5     ,  lowerCAmelCase__=5_0     ,  lowerCAmelCase__=1     ,  lowerCAmelCase__=4_2     ,  ):
       lowerCAmelCase__					     = torch.Generator(pipeline.device     ).manual_seed(lowerCAmelCase__     )
       lowerCAmelCase__					     = pipeline(
           lowerCAmelCase__     ,  guidance_scale=lowerCAmelCase__     ,  num_inference_steps=lowerCAmelCase__     ,  generator=lowerCAmelCase__     ,  num_images_per_prompt=lowerCAmelCase__     ,  ).images
       lowerCAmelCase__					     = int(math.sqrt(lowerCAmelCase__     )     )
       lowerCAmelCase__					     = image_grid(lowerCAmelCase__     ,  rows=_rows     ,  cols=num_images_per_prompt // _rows     )
       return grid, images


lowerCAmelCase__     						=			parse_args()
# Load models and create wrapper for stable diffusion
lowerCAmelCase__     						=			CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='tokenizer')
lowerCAmelCase__     						=			CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='text_encoder')
lowerCAmelCase__     						=			AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='vae')
lowerCAmelCase__     						=			UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='unet')

lowerCAmelCase__     						=			StableDiffusionPipeline.from_pretrained(
    args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
lowerCAmelCase__     						=			lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, 'best_model.pt')):
    lowerCAmelCase__     						=			load(args.pretrained_model_name_or_path, model=unet)
    unet.eval()
    setattr(pipeline, 'unet', unet)
else:
    lowerCAmelCase__     						=			unet.to(torch.device('cuda', args.cuda_id))
lowerCAmelCase__     						=			pipeline.to(unet.device)
lowerCAmelCase__						,		lowerCAmelCase__     						=			generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
grid.save(os.path.join(args.pretrained_model_name_or_path, '{}.png'.format('_'.join(args.caption.split()))))
lowerCAmelCase__     						=			os.path.join(args.pretrained_model_name_or_path, '_'.join(args.caption.split()))
os.makedirs(dirname, exist_ok=True)
for idx, image in enumerate(images):
    image.save(os.path.join(dirname, '{}.png'.format(idx + 1)))
