





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, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor



class        _SCREAMING_SNAKE_CASE						(     unittest.TestCase   ):







 '''simple docstring'''

 def __init__(self    :       List[str]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       int=7	,			UpperCAmelCase_    :       str=3	,			UpperCAmelCase_    :       List[str]=18	,			UpperCAmelCase_    :       Optional[int]=30	,			UpperCAmelCase_    :       Tuple=400	,			UpperCAmelCase_    :       Tuple=True	,			UpperCAmelCase_    :       Any=None	,			UpperCAmelCase_    :       int=True	,			UpperCAmelCase_    :       Optional[Any]=None	,			)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =size if size is not None else {"shortest_edge": 20}
   lowerCamelCase__:				Dict        =crop_size if crop_size is not None else {"height": 18, "width": 18}
   lowerCamelCase__:				List[str]        =parent
   lowerCamelCase__:				List[str]        =batch_size
   lowerCamelCase__:				str        =num_channels
   lowerCamelCase__:				str        =image_size
   lowerCamelCase__:				int        =min_resolution
   lowerCamelCase__:				int        =max_resolution
   lowerCamelCase__:				Dict        =do_resize
   lowerCamelCase__:				Dict        =size
   lowerCamelCase__:				List[str]        =do_center_crop
   lowerCamelCase__:				int        =crop_size







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



   '''simple docstring'''



   return {
       "do_resize": self.do_resize,
       "size": self.size,
       "do_center_crop": self.do_center_crop,
       "crop_size": self.crop_size,
   }



@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ,							unittest.TestCase   ):







 '''simple docstring'''
 lowercase_		=      MobileNetVaImageProcessor if is_vision_available() else None

 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =MobileNetVaImageProcessingTester(self)

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



   '''simple docstring'''



   return self.image_processor_tester.prepare_image_processor_dict()

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



   '''simple docstring'''



   lowerCamelCase__:				Tuple        =self.image_processing_class(**self.image_processor_dict)
   self.assertTrue(hasattr(UpperCAmelCase_	,			"do_resize"))
   self.assertTrue(hasattr(UpperCAmelCase_	,			"size"))
   self.assertTrue(hasattr(UpperCAmelCase_	,			"do_center_crop"))
   self.assertTrue(hasattr(UpperCAmelCase_	,			"crop_size"))

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



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self.image_processing_class.from_dict(self.image_processor_dict)
   self.assertEqual(image_processor.size	,			{"shortest_edge": 20})
   self.assertEqual(image_processor.crop_size	,			{"height": 18, "width": 18})

   lowerCamelCase__:				Tuple        =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 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->int:



   '''simple docstring'''



   pass

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



   '''simple docstring'''



   lowerCamelCase__:				Any        =self.image_processing_class(**self.image_processor_dict)
   # create random PIL images
   lowerCamelCase__:				Any        =prepare_image_inputs(self.image_processor_tester	,			equal_resolution=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_	,			Image.Image)

   # Test not batched input
   lowerCamelCase__:				Dict        =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
   lowerCamelCase__:				Dict        =image_processing(UpperCAmelCase_	,			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 							SCREAMING_SNAKE_CASE_ (self    :       Any)	->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:				str        =self.image_processing_class(**self.image_processor_dict)
   # create random numpy tensors
   lowerCamelCase__:				Dict        =prepare_image_inputs(self.image_processor_tester	,			equal_resolution=UpperCAmelCase_	,			numpify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_	,			np.ndarray)

   # Test not batched input
   lowerCamelCase__:				Union[str, 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
   lowerCamelCase__:				List[Any]        =image_processing(UpperCAmelCase_	,			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 							SCREAMING_SNAKE_CASE_ (self    :       str)	->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:				Tuple        =self.image_processing_class(**self.image_processor_dict)
   # create random PyTorch tensors
   lowerCamelCase__:				Tuple        =prepare_image_inputs(self.image_processor_tester	,			equal_resolution=UpperCAmelCase_	,			torchify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_	,			torch.Tensor)

   # Test not batched input
   lowerCamelCase__:				Tuple        =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
   lowerCamelCase__:				Tuple        =image_processing(UpperCAmelCase_	,			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"],
       )	,			)








from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand





def 					lowerCAmelCase_			(	__a		)					->		int:







  """simple docstring"""





  return ConvertCommand(
      args.model_type     ,   args.tf_checkpoint     ,   args.pytorch_dump_output     ,   args.config     ,   args.finetuning_task_name		)


__A     =    "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n"






class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       ArgumentParser)	->str:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =parser.add_parser(
       "convert"	,			help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints."	,			)
   train_parser.add_argument("--model_type"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Model's type.")
   train_parser.add_argument(
       "--tf_checkpoint"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="TensorFlow checkpoint path or folder.")
   train_parser.add_argument(
       "--pytorch_dump_output"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Path to the PyTorch saved model output.")
   train_parser.add_argument("--config"	,			type=UpperCAmelCase_	,			default=""	,			help="Configuration file path or folder.")
   train_parser.add_argument(
       "--finetuning_task_name"	,			type=UpperCAmelCase_	,			default=UpperCAmelCase_	,			help="Optional fine-tuning task name if the TF model was a finetuned model."	,			)
   train_parser.set_defaults(func=UpperCAmelCase_)

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			*UpperCAmelCase_    :       Optional[int]	,			)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =logging.get_logger("transformers-cli/converting")

   self._logger.info(F"""Loading model {model_type}""")
   lowerCamelCase__:				Any        =model_type
   lowerCamelCase__:				Optional[int]        =tf_checkpoint
   lowerCamelCase__:				Any        =pytorch_dump_output
   lowerCamelCase__:				Union[str, Any]        =config
   lowerCamelCase__:				str        =finetuning_task_name







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



   '''simple docstring'''



   if self._model_type == "albert":
     try:
       from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "bert":
     try:
       from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "funnel":
     try:
       from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
           convert_tf_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "t5":
     try:
       from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "gpt":
     from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
         convert_openai_checkpoint_to_pytorch,
     )

     convert_openai_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "transfo_xl":
     try:
       from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
           convert_transfo_xl_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     if "ckpt" in self._tf_checkpoint.lower():
       lowerCamelCase__:				Tuple        =self._tf_checkpoint
       lowerCamelCase__:				List[str]        =""
     else:
       lowerCamelCase__:				Any        =self._tf_checkpoint
       lowerCamelCase__:				Dict        =""
     convert_transfo_xl_checkpoint_to_pytorch(
         UpperCAmelCase_	,			self._config	,			self._pytorch_dump_output	,			UpperCAmelCase_)
   elif self._model_type == "gpt2":
     try:
       from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
           convert_gpta_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   elif self._model_type == "xlnet":
     try:
       from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
           convert_xlnet_checkpoint_to_pytorch,
       )
     except ImportError:
       raise ImportError(UpperCAmelCase_)

     convert_xlnet_checkpoint_to_pytorch(
         self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output	,			self._finetuning_task_name)
   elif self._model_type == "xlm":
     from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
         convert_xlm_checkpoint_to_pytorch,
     )

     convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint	,			self._pytorch_dump_output)
   elif self._model_type == "lxmert":
     from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
         convert_lxmert_checkpoint_to_pytorch,
     )

     convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint	,			self._pytorch_dump_output)
   elif self._model_type == "rembert":
     from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
         convert_rembert_tf_checkpoint_to_pytorch,
     )

     convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint	,			self._config	,			self._pytorch_dump_output)
   else:
     raise ValueError(
         "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]")

