





"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
       from PIL import Image

       from transformers import ViTImageProcessor







class       a							:



 def __init__(     self				,       _snake_case				,       _snake_case=13				,       _snake_case=30				,       _snake_case=2				,       _snake_case=3				,       _snake_case=True				,       _snake_case=True				,       _snake_case=32				,       _snake_case=2				,       _snake_case=4				,       _snake_case=37				,       _snake_case="gelu"				,       _snake_case=0.1				,       _snake_case=0.1				,       _snake_case=10				,       _snake_case=0.02				,       _snake_case=3				,       _snake_case=None				,       ):







  """simple docstring"""






  lowerCAmelCase    				= parent
  lowerCAmelCase    				= batch_size
  lowerCAmelCase    				= image_size
  lowerCAmelCase    				= patch_size
  lowerCAmelCase    				= num_channels
  lowerCAmelCase    				= is_training
  lowerCAmelCase    				= use_labels
  lowerCAmelCase    				= hidden_size
  lowerCAmelCase    				= num_hidden_layers
  lowerCAmelCase    				= num_attention_heads
  lowerCAmelCase    				= intermediate_size
  lowerCAmelCase    				= hidden_act
  lowerCAmelCase    				= hidden_dropout_prob
  lowerCAmelCase    				= attention_probs_dropout_prob
  lowerCAmelCase    				= type_sequence_label_size
  lowerCAmelCase    				= initializer_range
  lowerCAmelCase    				= scope

  # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
  lowerCAmelCase    				= (image_size // patch_size) ** 2
  lowerCAmelCase    				= num_patches + 1



 def    UpperCamelCase__  (     self     ):







  """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.type_sequence_label_size     )

  lowerCAmelCase    				= self.get_config()

  return config, pixel_values, labels



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return ViTConfig(
      image_size=self.image_size				,       patch_size=self.patch_size				,       num_channels=self.num_channels				,       hidden_size=self.hidden_size				,       num_hidden_layers=self.num_hidden_layers				,       num_attention_heads=self.num_attention_heads				,       intermediate_size=self.intermediate_size				,       hidden_act=self.hidden_act				,       hidden_dropout_prob=self.hidden_dropout_prob				,       attention_probs_dropout_prob=self.attention_probs_dropout_prob				,       is_decoder=_snake_case				,       initializer_range=self.initializer_range				,       )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= TFViTModel(config=_snake_case     )
  lowerCAmelCase    				= model(_snake_case				,       training=_snake_case     )
  self.parent.assertEqual(result.last_hidden_state.shape				,       (self.batch_size, self.seq_length, self.hidden_size)     )

  # Test with an image with different size than the one specified in config.
  lowerCAmelCase    				= self.image_size // 2
  lowerCAmelCase    				= pixel_values[:, :, :image_size, :image_size]
  lowerCAmelCase    				= model(_snake_case				,       interpolate_pos_encoding=_snake_case				,       training=_snake_case     )
  lowerCAmelCase    				= (image_size // self.patch_size) ** 2 + 1
  self.parent.assertEqual(result.last_hidden_state.shape				,       (self.batch_size, seq_length, self.hidden_size)     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= self.type_sequence_label_size
  lowerCAmelCase    				= TFViTForImageClassification(_snake_case     )
  lowerCAmelCase    				= model(_snake_case				,       labels=_snake_case				,       training=_snake_case     )
  self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.type_sequence_label_size)     )

  # Test with an image with different size than the one specified in config.
  lowerCAmelCase    				= self.image_size // 2
  lowerCAmelCase    				= pixel_values[:, :, :image_size, :image_size]
  lowerCAmelCase    				= model(_snake_case				,       interpolate_pos_encoding=_snake_case				,       training=_snake_case     )
  self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.type_sequence_label_size)     )

  # test greyscale images
  lowerCAmelCase    				= 1
  lowerCAmelCase    				= TFViTForImageClassification(_snake_case     )
  lowerCAmelCase    				= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
  lowerCAmelCase    				= model(_snake_case     )
  self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.type_sequence_label_size)     )



 def    UpperCamelCase__  (     self     ):







  """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							(   a__   , a__   , unittest.TestCase  ):
 snake_case__             =       (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
 snake_case__             =       (
     {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
     if is_tf_available()
     else {}
 )

 snake_case__             =       False
 snake_case__             =       False
 snake_case__             =       False



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= TFViTModelTester(self     )
  lowerCAmelCase    				= ConfigTester(self				,       config_class=_snake_case				,       has_text_modality=_snake_case				,       hidden_size=37     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self.config_tester.run_common_tests()



 @unittest.skip(reason='ViT does not use inputs_embeds'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 @unittest.skip(reason='ViT does not use inputs_embeds'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   lowerCAmelCase    				= model_class(_snake_case     )
   self.assertIsInstance(model.get_input_embeddings()				,       (tf.keras.layers.Layer)     )
   lowerCAmelCase    				= model.get_output_embeddings()
   self.assertTrue(x is None or isinstance(_snake_case				,       tf.keras.layers.Layer     )     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   lowerCAmelCase    				= model_class(_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]				,       _snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*_snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_image_classification(*_snake_case     )



 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= TFViTModel.from_pretrained('google/vit-base-patch16-224'     )
  self.assertIsNotNone(_snake_case     )


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







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



 @cached_property
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'     ) if is_vision_available() else None



 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'     )

  lowerCAmelCase    				= self.default_image_processor
  lowerCAmelCase    				= prepare_img()
  lowerCAmelCase    				= image_processor(images=_snake_case				,       return_tensors='tf'     )

  # forward pass
  lowerCAmelCase    				= model(**_snake_case     )

  # verify the logits
  lowerCAmelCase    				= tf.TensorShape((1, 10_00)     )
  self.assertEqual(outputs.logits.shape				,       _snake_case     )

  lowerCAmelCase    				= tf.constant([-0.2_744, 0.8_215, -0.0_836]     )

  tf.debugging.assert_near(outputs.logits[0, :3]				,       _snake_case				,       atol=1E-4     )












"""simple docstring"""
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 		_SCREAMING_SNAKE_CASE			():
 lowerCAmelCase    				= argparse.ArgumentParser()
 parser.add_argument(
     '-m'  ,     '--pretrained_model_name_or_path'  ,     type=_UpperCAmelCase  ,     default=_UpperCAmelCase  ,     required=_UpperCAmelCase  ,     help='Path to pretrained model or model identifier from huggingface.co/models.'  ,     )
 parser.add_argument(
     '-c'  ,     '--caption'  ,     type=_UpperCAmelCase  ,     default='robotic cat with wings'  ,     help='Text used to generate images.'  ,     )
 parser.add_argument(
     '-n'  ,     '--images_num'  ,     type=_UpperCAmelCase  ,     default=4  ,     help='How much images to generate.'  ,     )
 parser.add_argument(
     '-s'  ,     '--seed'  ,     type=_UpperCAmelCase  ,     default=42  ,     help='Seed for random process.'  ,     )
 parser.add_argument(
     '-ci'  ,     '--cuda_id'  ,     type=_UpperCAmelCase  ,     default=0  ,     help='cuda_id.'  ,     )
 lowerCAmelCase    				= parser.parse_args()
 return args

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    int  ,     _UpperCAmelCase					:    List[Any]  ,     _UpperCAmelCase					:    Optional[int]			):
 if not len(_UpperCAmelCase			) == 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(_UpperCAmelCase			):
  grid.paste(_UpperCAmelCase  ,     box=(i % cols * w, i // cols * h)			)
 return grid

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    Any  ,     _UpperCAmelCase					:    Union[str, Any]="robotic cat with wings"  ,     _UpperCAmelCase					:    Optional[int]=7.5  ,     _UpperCAmelCase					:    Dict=50  ,     _UpperCAmelCase					:    Tuple=1  ,     _UpperCAmelCase					:    int=42  ,     ):
 lowerCAmelCase    				= torch.Generator(pipeline.device			).manual_seed(_UpperCAmelCase			)
 lowerCAmelCase    				= pipeline(
     _UpperCAmelCase  ,     guidance_scale=_UpperCAmelCase  ,     num_inference_steps=_UpperCAmelCase  ,     generator=_UpperCAmelCase  ,     num_images_per_prompt=_UpperCAmelCase  ,     ).images
 lowerCAmelCase    				= int(math.sqrt(_UpperCAmelCase			)			)
 lowerCAmelCase    				= image_grid(_UpperCAmelCase  ,     rows=_rows  ,     cols=num_images_per_prompt // _rows			)
 return grid, images


__UpperCamelCase     :						Optional[Any]						       =  parse_args()
# Load models and create wrapper for stable diffusion
__UpperCamelCase     :						List[Any]						       =  CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='''tokenizer''')
__UpperCamelCase     :						str						       =  CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''text_encoder''')
__UpperCamelCase     :						Optional[int]						       =  AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='''vae''')
__UpperCamelCase     :						List[str]						       =  UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''unet''')

__UpperCamelCase     :						Tuple						       =  StableDiffusionPipeline.from_pretrained(
    args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
__UpperCamelCase     :						Union[str, Any]						       =  lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, '''best_model.pt''')):
       __UpperCamelCase     :						Dict						       =  load(args.pretrained_model_name_or_path, model=unet)
       unet.eval()
       setattr(pipeline, '''unet''', unet)
else:
       __UpperCamelCase     :						Dict						       =  unet.to(torch.device('''cuda''', args.cuda_id))
__UpperCamelCase     :						Optional[Any]						       =  pipeline.to(unet.device)
__UpperCamelCase       ,__UpperCamelCase     :						List[Any]						       =  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()))))
__UpperCamelCase     :						int						       =  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)))





