




import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List

from ..utils import logging
from . import BaseTransformersCLICommand


try:
     from cookiecutter.main import cookiecutter

     UpperCamelCase								=	True
except ImportError:
     UpperCamelCase								=	False

UpperCamelCase								=	logging.get_logger(__name__)  # pylint: disable=invalid-name



def 				_A  (		lowerCAmelCase_	:   Namespace     ):
     """simple docstring"""

     return AddNewModelCommand(args.testing  ,							args.testing_file  ,							path=args.path     )






class 					__lowerCamelCase			(       UpperCamelCase__       ):




    """simple docstring"""

    @staticmethod
    def   a (			SCREAMING_SNAKE_CASE__	:	ArgumentParser  ) ->			int:
         lowerCAmelCase__            =					parser.add_parser("add-new-model"  )
         add_new_model_parser.add_argument("--testing"  ,      action="store_true"  ,      help="If in testing mode."  )
         add_new_model_parser.add_argument("--testing_file"  ,      type=SCREAMING_SNAKE_CASE__  ,      help="Configuration file on which to run."  )
         add_new_model_parser.add_argument(
             "--path"  ,      type=SCREAMING_SNAKE_CASE__  ,      help="Path to cookiecutter. Should only be used for testing purposes."  )
         add_new_model_parser.set_defaults(func=SCREAMING_SNAKE_CASE__  )


    def __init__(			self	:	Tuple  ,      SCREAMING_SNAKE_CASE__	:	bool  ,      SCREAMING_SNAKE_CASE__	:	str  ,      SCREAMING_SNAKE_CASE__	:	Optional[Any]=None  ,      *SCREAMING_SNAKE_CASE__	:	Tuple  ) ->			List[Any]:
         lowerCAmelCase__            =					testing
         lowerCAmelCase__            =					testing_file
         lowerCAmelCase__            =					path


    def   a (			self	:	Union[str, Any]  ) ->			Tuple:
         warnings.warn(
             "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. "
             "It is not actively maintained anymore, so might give a result that won't pass all tests and quality "
             "checks, you should use `transformers-cli add-new-model-like` instead."  )
         if not _has_cookiecutter:
              raise ImportError(
                  "Model creation dependencies are required to use the `add_new_model` command. Install them by running "
                  "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n"  )
         # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
         lowerCAmelCase__            =					[directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]]
         if len(SCREAMING_SNAKE_CASE__  ) > 0:
              raise ValueError(
                  "Several directories starting with `cookiecutter-template-` in current working directory. "
                  "Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
                  "change your working directory."  )

         lowerCAmelCase__            =					(
             Path(SCREAMING_SNAKE_CASE__  ).parent.parent.parent.parent if self._path is None else Path(self._path  ).parent.parent
         )
         lowerCAmelCase__            =					path_to_transformer_root / "templates" / "adding_a_new_model"

         # Execute cookiecutter
         if not self._testing:
              cookiecutter(str(SCREAMING_SNAKE_CASE__  )  )
         else:
              with open(self._testing_file  ,      "r"  ) as configuration_file:
                   lowerCAmelCase__            =					json.load(SCREAMING_SNAKE_CASE__  )

              cookiecutter(
                  str(path_to_cookiecutter if self._path is None else self._path  )  ,      no_input=SCREAMING_SNAKE_CASE__  ,      extra_context=SCREAMING_SNAKE_CASE__  ,      )

         lowerCAmelCase__            =					[directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0]

         # Retrieve configuration
         with open(directory + "/configuration.json"  ,      "r"  ) as configuration_file:
              lowerCAmelCase__            =					json.load(SCREAMING_SNAKE_CASE__  )

         lowerCAmelCase__            =					configuration["lowercase_modelname"]
         lowerCAmelCase__            =					configuration["generate_tensorflow_pytorch_and_flax"]
         os.remove(f'{directory}/configuration.json'  )

         lowerCAmelCase__            =					"PyTorch" in generate_tensorflow_pytorch_and_flax
         lowerCAmelCase__            =					"TensorFlow" in generate_tensorflow_pytorch_and_flax
         lowerCAmelCase__            =					"Flax" in generate_tensorflow_pytorch_and_flax

         lowerCAmelCase__            =					f'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}'
         os.makedirs(SCREAMING_SNAKE_CASE__  ,      exist_ok=SCREAMING_SNAKE_CASE__  )
         os.makedirs(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}'  ,      exist_ok=SCREAMING_SNAKE_CASE__  )

         # Tests require submodules as they have parent imports
         with open(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py'  ,      "w"  ):
              pass

         shutil.move(
             f'{directory}/__init__.py'  ,      f'{model_dir}/__init__.py'  ,      )
         shutil.move(
             f'{directory}/configuration_{lowercase_model_name}.py'  ,      f'{model_dir}/configuration_{lowercase_model_name}.py'  ,      )

         def remove_copy_lines(SCREAMING_SNAKE_CASE__	:	Dict  ):
              with open(SCREAMING_SNAKE_CASE__  ,      "r"  ) as f:
                   lowerCAmelCase__            =					f.readlines()
              with open(SCREAMING_SNAKE_CASE__  ,      "w"  ) as f:
                   for line in lines:
                        if "# Copied from transformers." not in line:
                             f.write(SCREAMING_SNAKE_CASE__  )

         if output_pytorch:
              if not self._testing:
                   remove_copy_lines(f'{directory}/modeling_{lowercase_model_name}.py'  )

              shutil.move(
                  f'{directory}/modeling_{lowercase_model_name}.py'  ,      f'{model_dir}/modeling_{lowercase_model_name}.py'  ,      )

              shutil.move(
                  f'{directory}/test_modeling_{lowercase_model_name}.py'  ,      f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py'  ,      )
         else:
              os.remove(f'{directory}/modeling_{lowercase_model_name}.py'  )
              os.remove(f'{directory}/test_modeling_{lowercase_model_name}.py'  )

         if output_tensorflow:
              if not self._testing:
                   remove_copy_lines(f'{directory}/modeling_tf_{lowercase_model_name}.py'  )

              shutil.move(
                  f'{directory}/modeling_tf_{lowercase_model_name}.py'  ,      f'{model_dir}/modeling_tf_{lowercase_model_name}.py'  ,      )

              shutil.move(
                  f'{directory}/test_modeling_tf_{lowercase_model_name}.py'  ,      f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py'  ,      )
         else:
              os.remove(f'{directory}/modeling_tf_{lowercase_model_name}.py'  )
              os.remove(f'{directory}/test_modeling_tf_{lowercase_model_name}.py'  )

         if output_flax:
              if not self._testing:
                   remove_copy_lines(f'{directory}/modeling_flax_{lowercase_model_name}.py'  )

              shutil.move(
                  f'{directory}/modeling_flax_{lowercase_model_name}.py'  ,      f'{model_dir}/modeling_flax_{lowercase_model_name}.py'  ,      )

              shutil.move(
                  f'{directory}/test_modeling_flax_{lowercase_model_name}.py'  ,      f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py'  ,      )
         else:
              os.remove(f'{directory}/modeling_flax_{lowercase_model_name}.py'  )
              os.remove(f'{directory}/test_modeling_flax_{lowercase_model_name}.py'  )

         shutil.move(
             f'{directory}/{lowercase_model_name}.md'  ,      f'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md'  ,      )

         shutil.move(
             f'{directory}/tokenization_{lowercase_model_name}.py'  ,      f'{model_dir}/tokenization_{lowercase_model_name}.py'  ,      )

         shutil.move(
             f'{directory}/tokenization_fast_{lowercase_model_name}.py'  ,      f'{model_dir}/tokenization_{lowercase_model_name}_fast.py'  ,      )

         from os import fdopen, remove
         from shutil import copymode, move
         from tempfile import mkstemp

         def replace(SCREAMING_SNAKE_CASE__	:	str  ,      SCREAMING_SNAKE_CASE__	:	str  ,      SCREAMING_SNAKE_CASE__	:	List[str]  ):
              # Create temp file
              lowerCAmelCase__      ,						lowerCAmelCase__            =					mkstemp()
              lowerCAmelCase__            =					False
              with fdopen(SCREAMING_SNAKE_CASE__  ,      "w"  ) as new_file:
                   with open(SCREAMING_SNAKE_CASE__  ) as old_file:
                        for line in old_file:
                             new_file.write(SCREAMING_SNAKE_CASE__  )
                             if line_to_copy_below in line:
                                  lowerCAmelCase__            =					True
                                  for line_to_copy in lines_to_copy:
                                       new_file.write(SCREAMING_SNAKE_CASE__  )

              if not line_found:
                   raise ValueError(f'Line {line_to_copy_below} was not found in file.'  )

              # Copy the file permissions from the old file to the new file
              copymode(SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  )
              # Remove original file
              remove(SCREAMING_SNAKE_CASE__  )
              # Move new file
              move(SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  )

         def skip_units(SCREAMING_SNAKE_CASE__	:	List[Any]  ):
              return (
                  ("generating PyTorch" in line and not output_pytorch)
                  or ("generating TensorFlow" in line and not output_tensorflow)
                  or ("generating Flax" in line and not output_flax)
              )

         def replace_in_files(SCREAMING_SNAKE_CASE__	:	List[Any]  ):
              with open(SCREAMING_SNAKE_CASE__  ) as datafile:
                   lowerCAmelCase__            =					[]
                   lowerCAmelCase__            =					False
                   lowerCAmelCase__            =					False
                   for line in datafile:
                        if "# To replace in: " in line and "##" not in line:
                             lowerCAmelCase__            =					line.split("\""  )[1]
                             lowerCAmelCase__            =					skip_units(SCREAMING_SNAKE_CASE__  )
                        elif "# Below: " in line and "##" not in line:
                             lowerCAmelCase__            =					line.split("\""  )[1]
                             lowerCAmelCase__            =					skip_units(SCREAMING_SNAKE_CASE__  )
                        elif "# End." in line and "##" not in line:
                             if not skip_file and not skip_snippet:
                                  replace(SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  )

                             lowerCAmelCase__            =					[]
                        elif "# Replace with" in line and "##" not in line:
                             lowerCAmelCase__            =					[]
                        elif "##" not in line:
                             lines_to_copy.append(SCREAMING_SNAKE_CASE__  )

              remove(SCREAMING_SNAKE_CASE__  )

         replace_in_files(f'{directory}/to_replace_{lowercase_model_name}.py'  )
         os.rmdir(SCREAMING_SNAKE_CASE__  )








'''simple docstring'''



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)


def 				lowercase_					(     __A			:							Tuple      )							->   List[List[ImageInput]]:



 """simple docstring"""




 if isinstance(__A       ,   (list, tuple)      ) and isinstance(videos[0]       ,   (list, tuple)      ) and is_valid_image(videos[0][0]      ):
  return videos

 elif isinstance(__A       ,   (list, tuple)      ) and is_valid_image(videos[0]      ):
  return [videos]

 elif is_valid_image(__A      ):
  return [[videos]]

 raise ValueError(F'Could not make batched video from {videos}'      )





class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ['''pixel_values''']






      def __init__(			self      :		List[Any]  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = PILImageResampling.BILINEAR  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Union[int, float] = 1 / 255  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   **UpperCAmelCase      :		Tuple  ,   )	->	None:


       '''simple docstring'''

       super().__init__(**UpperCAmelCase		)
       lowercase       : Tuple						=size if size is not None else {'''shortest_edge''': 224}
       lowercase       : str						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       lowercase       : List[str]						=crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
       lowercase       : List[Any]						=get_size_dict(UpperCAmelCase  ,   param_name='''crop_size'''		)

       lowercase       : Tuple						=do_resize
       lowercase       : Any						=size
       lowercase       : Optional[Any]						=do_center_crop
       lowercase       : str						=crop_size
       lowercase       : Any						=resample
       lowercase       : List[Any]						=do_rescale
       lowercase       : Dict						=rescale_factor
       lowercase       : List[str]						=do_normalize
       lowercase       : Optional[int]						=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       lowercase       : List[Any]						=image_std if image_std is not None else IMAGENET_STANDARD_STD






      def 					A__   (			self      :		Dict  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Dict[str, int]  ,   UpperCAmelCase      :		PILImageResampling = PILImageResampling.BILINEAR  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		List[str]  ,   )	->	np.ndarray:


       '''simple docstring'''

       lowercase       : str						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       if "shortest_edge" in size:
        lowercase       : int						=get_resize_output_image_size(UpperCAmelCase  ,   size['''shortest_edge''']  ,   default_to_square=UpperCAmelCase		)
       elif "height" in size and "width" in size:
        lowercase       : str						=(size['''height'''], size['''width'''])
       else:
        raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'		)
       return resize(UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Dict[str, int]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		Optional[Any]  ,   )	->	np.ndarray:


       '''simple docstring'''

       lowercase       : List[str]						=get_size_dict(UpperCAmelCase		)
       if "height" not in size or "width" not in size:
        raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}'		)
       return center_crop(UpperCAmelCase  ,   size=(size['''height'''], size['''width'''])  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Union[int, float]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		Tuple  ,   )	->	List[Any]:


       '''simple docstring'''

       return rescale(UpperCAmelCase  ,   scale=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Union[float, List[float]]  ,   UpperCAmelCase      :		Union[float, List[float]]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		int  ,   )	->	np.ndarray:


       '''simple docstring'''

       return normalize(UpperCAmelCase  ,   mean=UpperCAmelCase  ,   std=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		ImageInput  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		float = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[ChannelDimension] = ChannelDimension.FIRST  ,   )	->	np.ndarray:


       '''simple docstring'''

       if do_resize and size is None or resample is None:
        raise ValueError('''Size and resample must be specified if do_resize is True.'''		)

       if do_center_crop and crop_size is None:
        raise ValueError('''Crop size must be specified if do_center_crop is True.'''		)

       if do_rescale and rescale_factor is None:
        raise ValueError('''Rescale factor must be specified if do_rescale is True.'''		)

       if do_normalize and (image_mean is None or image_std is None):
        raise ValueError('''Image mean and std must be specified if do_normalize is True.'''		)

       # All transformations expect numpy arrays.
       lowercase       : Dict						=to_numpy_array(UpperCAmelCase		)

       if do_resize:
        lowercase       : Union[str, Any]						=self.resize(image=UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase		)

       if do_center_crop:
        lowercase       : Optional[Any]						=self.center_crop(UpperCAmelCase  ,   size=UpperCAmelCase		)

       if do_rescale:
        lowercase       : Dict						=self.rescale(image=UpperCAmelCase  ,   scale=UpperCAmelCase		)

       if do_normalize:
        lowercase       : int						=self.normalize(image=UpperCAmelCase  ,   mean=UpperCAmelCase  ,   std=UpperCAmelCase		)

       lowercase       : Optional[Any]						=to_channel_dimension_format(UpperCAmelCase  ,   UpperCAmelCase		)
       return image






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		ImageInput  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		float = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[str, TensorType]] = None  ,   UpperCAmelCase      :		ChannelDimension = ChannelDimension.FIRST  ,   **UpperCAmelCase      :		Optional[int]  ,   )	->	PIL.Image.Image:


       '''simple docstring'''

       lowercase       : Any						=do_resize if do_resize is not None else self.do_resize
       lowercase       : Union[str, Any]						=resample if resample is not None else self.resample
       lowercase       : Tuple						=do_center_crop if do_center_crop is not None else self.do_center_crop
       lowercase       : List[Any]						=do_rescale if do_rescale is not None else self.do_rescale
       lowercase       : str						=rescale_factor if rescale_factor is not None else self.rescale_factor
       lowercase       : List[str]						=do_normalize if do_normalize is not None else self.do_normalize
       lowercase       : List[str]						=image_mean if image_mean is not None else self.image_mean
       lowercase       : Optional[int]						=image_std if image_std is not None else self.image_std

       lowercase       : Optional[Any]						=size if size is not None else self.size
       lowercase       : Any						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       lowercase       : Union[str, Any]						=crop_size if crop_size is not None else self.crop_size
       lowercase       : Optional[int]						=get_size_dict(UpperCAmelCase  ,   param_name='''crop_size'''		)

       if not valid_images(UpperCAmelCase		):
        raise ValueError(
            '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
            '''torch.Tensor, tf.Tensor or jax.ndarray.'''		)

       lowercase       : List[str]						=make_batched(UpperCAmelCase		)

       lowercase       : Union[str, Any]						=[
           [
               self._preprocess_image(
                   image=UpperCAmelCase  ,   do_resize=UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase  ,   do_center_crop=UpperCAmelCase  ,   crop_size=UpperCAmelCase  ,   do_rescale=UpperCAmelCase  ,   rescale_factor=UpperCAmelCase  ,   do_normalize=UpperCAmelCase  ,   image_mean=UpperCAmelCase  ,   image_std=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   )
               for img in video
           ]
           for video in videos
       ]

       lowercase       : Dict						={'''pixel_values''': videos}
       return BatchFeature(data=UpperCAmelCase  ,   tensor_type=UpperCAmelCase		)



