





import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import ChineseCLIPImageProcessor





class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=7 ,  lowercase=3 ,  lowercase=18 ,  lowercase=30 ,  lowercase=400 ,  lowercase=True ,  lowercase=None ,  lowercase=True ,  lowercase=None ,  lowercase=True ,  lowercase=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] ,  lowercase=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] ,  lowercase=True ,  )      ->						Optional[int]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    size if size is not None else {'height': 224, 'width': 224}
          a__						:     Optional[int]			=    crop_size if crop_size is not None else {'height': 18, 'width': 18}
          a__						:     str			=    parent
          a__						:     Any			=    batch_size
          a__						:     Dict			=    num_channels
          a__						:     Optional[int]			=    image_size
          a__						:     Optional[Any]			=    min_resolution
          a__						:     int			=    max_resolution
          a__						:     List[str]			=    do_resize
          a__						:     Tuple			=    size
          a__						:     List[Any]			=    do_center_crop
          a__						:     Optional[int]			=    crop_size
          a__						:     Dict			=    do_normalize
          a__						:     Dict			=    image_mean
          a__						:     Any			=    image_std
          a__						:     List[str]			=    do_convert_rgb

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
              "do_normalize": self.do_normalize,
              "image_mean": self.image_mean,
              "image_std": self.image_std,
              "do_convert_rgb": self.do_convert_rgb,
          }

   def 							__lowercase		( self ,  lowercase=False ,  lowercase=False ,  lowercase=False)      ->						Optional[Any]:







          '''simple docstring'''

          assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

          if equal_resolution:
                 a__						:     Dict			=    []
                 for i in range(self.batch_size):
                        image_inputs.append(
                            np.random.randint(
                                255 ,  size=(self.num_channels, self.max_resolution, self.max_resolution) ,  dtype=np.uinta))
          else:
                 a__						:     List[Any]			=    []
                 for i in range(self.batch_size):
                        a__			,							a__						:     Dict			=    np.random.choice(np.arange(self.min_resolution ,  self.max_resolution) ,  2)
                        image_inputs.append(np.random.randint(255 ,  size=(self.num_channels, width, height) ,  dtype=np.uinta))

          if not numpify and not torchify:
                 # PIL expects the channel dimension as last dimension
                 a__						:     List[str]			=    [Image.fromarray(np.moveaxis(lowercase ,  0 ,  -1)) for x in image_inputs]

          if torchify:
                 a__						:     Optional[int]			=    [torch.from_numpy(lowercase) for x in image_inputs]

          return image_inputs





@require_torch
@require_vision
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   __A       :    Tuple	  =  ChineseCLIPImageProcessor if is_vision_available() else None

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    ChineseCLIPImageProcessingTester(self ,  do_center_crop=lowercase)

   @property
   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          return self.image_processor_tester.prepare_image_processor_dict()

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Dict			=    self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(lowercase ,  'do_resize'))
          self.assertTrue(hasattr(lowercase ,  'size'))
          self.assertTrue(hasattr(lowercase ,  'do_center_crop'))
          self.assertTrue(hasattr(lowercase ,  'center_crop'))
          self.assertTrue(hasattr(lowercase ,  'do_normalize'))
          self.assertTrue(hasattr(lowercase ,  'image_mean'))
          self.assertTrue(hasattr(lowercase ,  'image_std'))
          self.assertTrue(hasattr(lowercase ,  'do_convert_rgb'))

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Dict			=    self.image_processing_class.from_dict(self.image_processor_dict)
          self.assertEqual(image_processor.size ,  {'height': 224, 'width': 224})
          self.assertEqual(image_processor.crop_size ,  {'height': 18, 'width': 18})

          a__						:     Dict			=    self.image_processing_class.from_dict(self.image_processor_dict ,  size=42 ,  crop_size=84)
          self.assertEqual(image_processor.size ,  {'shortest_edge': 42})
          self.assertEqual(image_processor.crop_size ,  {'height': 84, 'width': 84})

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     List[str]			=    self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          a__						:     Optional[Any]			=    self.image_processor_tester.prepare_inputs(equal_resolution=lowercase)
          for image in image_inputs:
                 self.assertIsInstance(lowercase ,  Image.Image)

          # Test not batched input
          a__						:     Optional[int]			=    image_processing(image_inputs[0] ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

          # Test batched
          a__						:     List[str]			=    image_processing(lowercase ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     List[str]			=    self.image_processing_class(**self.image_processor_dict)
          # create random numpy tensors
          a__						:     Dict			=    self.image_processor_tester.prepare_inputs(equal_resolution=lowercase ,  numpify=lowercase)
          for image in image_inputs:
                 self.assertIsInstance(lowercase ,  np.ndarray)

          # Test not batched input
          a__						:     Any			=    image_processing(image_inputs[0] ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

          # Test batched
          a__						:     int			=    image_processing(lowercase ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[int]			=    self.image_processing_class(**self.image_processor_dict)
          # create random PyTorch tensors
          a__						:     Dict			=    self.image_processor_tester.prepare_inputs(equal_resolution=lowercase ,  torchify=lowercase)
          for image in image_inputs:
                 self.assertIsInstance(lowercase ,  torch.Tensor)

          # Test not batched input
          a__						:     List[Any]			=    image_processing(image_inputs[0] ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

          # Test batched
          a__						:     Optional[int]			=    image_processing(lowercase ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )





@require_torch
@require_vision
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   __A       :    Dict	  =  ChineseCLIPImageProcessor if is_vision_available() else None

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          a__						:     Dict			=    ChineseCLIPImageProcessingTester(self ,  num_channels=4 ,  do_center_crop=lowercase)
          a__						:     Dict			=    3

   @property
   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          return self.image_processor_tester.prepare_image_processor_dict()

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     Dict			=    self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(lowercase ,  'do_resize'))
          self.assertTrue(hasattr(lowercase ,  'size'))
          self.assertTrue(hasattr(lowercase ,  'do_center_crop'))
          self.assertTrue(hasattr(lowercase ,  'center_crop'))
          self.assertTrue(hasattr(lowercase ,  'do_normalize'))
          self.assertTrue(hasattr(lowercase ,  'image_mean'))
          self.assertTrue(hasattr(lowercase ,  'image_std'))
          self.assertTrue(hasattr(lowercase ,  'do_convert_rgb'))

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          a__						:     List[str]			=    self.image_processor_tester.prepare_inputs(equal_resolution=lowercase)
          for image in image_inputs:
                 self.assertIsInstance(lowercase ,  Image.Image)

          # Test not batched input
          a__						:     str			=    image_processing(image_inputs[0] ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  1,
                  self.expected_encoded_image_num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )

          # Test batched
          a__						:     Dict			=    image_processing(lowercase ,  return_tensors='pt').pixel_values
          self.assertEqual(
              encoded_images.shape ,  (
                  self.image_processor_tester.batch_size,
                  self.expected_encoded_image_num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              ) ,  )









import argparse

import torch

from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()



def A_     (		A__		,				A__		,				A__    )  ->		Any:
       # Construct model
       if gpta_config_file == "":
              a__						:     Optional[int]			=    GPTaConfig()
       else:
              a__						:     List[str]			=    GPTaConfig.from_json_file(A__    )
       a__						:     List[str]			=    GPTaModel(A__    )

       # Load weights from numpy
       load_tf_weights_in_gpta(A__		,				A__		,				A__    )

       # Save pytorch-model
       a__						:     Optional[Any]			=    pytorch_dump_folder_path + '/' + WEIGHTS_NAME
       a__						:     Any			=    pytorch_dump_folder_path + '/' + CONFIG_NAME
       print(F'Save PyTorch model to {pytorch_weights_dump_path}'    )
       torch.save(model.state_dict()		,				A__    )
       print(F'Save configuration file to {pytorch_config_dump_path}'    )
       with open(A__		,				'w'		,				encoding='utf-8'    ) as f:
              f.write(config.to_json_string()    )


if __name__ == "__main__":
    lowercase				:	Dict      						=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
    )
    parser.add_argument(
        """--gpt2_config_file""",
        default="""""",
        type=str,
        help=(
            """An optional config json file corresponding to the pre-trained OpenAI model. \n"""
            """This specifies the model architecture."""
        ),
    )
    lowercase				:	int      						=  parser.parse_args()
    convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)


