from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor
class     a_			:






 '''simple docstring'''






 def __init__(      self :  str      ,   lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]=3      ,   lowercase__ :  Any=32      ,   lowercase__ :  Optional[int]=3      ,   lowercase__ :  Any=10      ,   lowercase__ :  List[str]=[10, 20, 30, 40]      ,   lowercase__ :  List[str]=[1, 1, 2, 1]      ,   lowercase__ :  Optional[int]=True      ,   lowercase__ :  int=True      ,   lowercase__ :  Any="relu"      ,   lowercase__ :  List[Any]=3      ,   lowercase__ :  Union[str, Any]=None      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = parent
        lowerCAmelCase__					     = batch_size
        lowerCAmelCase__					     = image_size
        lowerCAmelCase__					     = num_channels
        lowerCAmelCase__					     = embeddings_size
        lowerCAmelCase__					     = hidden_sizes
        lowerCAmelCase__					     = depths
        lowerCAmelCase__					     = is_training
        lowerCAmelCase__					     = use_labels
        lowerCAmelCase__					     = hidden_act
        lowerCAmelCase__					     = num_labels
        lowerCAmelCase__					     = scope
        lowerCAmelCase__					     = len(_SCREAMING_SNAKE_CASE)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



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

        lowerCAmelCase__					     = None
        if self.use_labels:
               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 ResNetConfig(
            num_channels=self.num_channels      ,   embeddings_size=self.embeddings_size      ,   hidden_sizes=self.hidden_sizes      ,   depths=self.depths      ,   hidden_act=self.hidden_act      ,   num_labels=self.num_labels      ,   image_size=self.image_size      ,   )




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







        '''simple docstring'''



        lowerCAmelCase__					     = TFResNetModel(config=_SCREAMING_SNAKE_CASE)
        lowerCAmelCase__					     = model(_SCREAMING_SNAKE_CASE)
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape      ,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)      ,   )




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







        '''simple docstring'''



        lowerCAmelCase__					     = self.num_labels
        lowerCAmelCase__					     = TFResNetForImageClassification(_SCREAMING_SNAKE_CASE)
        lowerCAmelCase__					     = model(_SCREAMING_SNAKE_CASE      ,   labels=_SCREAMING_SNAKE_CASE)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels))




 def 		__snake_case						(      self :  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_			(						_UpperCamelCase	,					_UpperCamelCase	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 UpperCAmelCase_     			= (
     {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = TFResNetModelTester(self)
        lowerCAmelCase__					     = ConfigTester(self      ,   config_class=_SCREAMING_SNAKE_CASE      ,   has_text_modality=_SCREAMING_SNAKE_CASE)




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        self.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()




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        return




 @unittest.skip(reason='ResNet does not use inputs_embeds')
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        pass




 @unittest.skip(reason='ResNet does not support input and output embeddings')
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        pass




 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(_SCREAMING_SNAKE_CASE)
               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]      ,   _SCREAMING_SNAKE_CASE)




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        def check_hidden_states_output(lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Dict):
               lowerCAmelCase__					     = model_class(_SCREAMING_SNAKE_CASE)
               lowerCAmelCase__					     = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE))

               lowerCAmelCase__					     = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               lowerCAmelCase__					     = self.model_tester.num_stages
               self.assertEqual(len(_SCREAMING_SNAKE_CASE)      ,   expected_num_stages + 1)

               # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:])      ,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]      ,   )

        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase__					     = ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
               for layer_type in layers_type:
                      lowerCAmelCase__					     = layer_type
                      lowerCAmelCase__					     = True
                      check_hidden_states_output(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE)

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

                      check_hidden_states_output(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



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




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







        '''simple docstring'''



        for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowerCAmelCase__					     = TFResNetModel.from_pretrained(_SCREAMING_SNAKE_CASE)
               self.assertIsNotNone(_SCREAMING_SNAKE_CASE)






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 :  Tuple):







        '''simple docstring'''



        return (
            AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
            if is_vision_available()
            else None
        )




 @slow
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

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

        # forward pass
        lowerCAmelCase__					     = model(**_SCREAMING_SNAKE_CASE)

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

        lowerCAmelCase__					     = tf.constant([-11.1_069, -9.7_877, -8.3_777])

        self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,   _SCREAMING_SNAKE_CASE      ,   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)))
