

"""simple docstring"""





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

   _a       =							True
except ImportError:
   _a       =							False

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




def   _A  (  UpperCamelCase_     :       Namespace)	->						List[Any]:
   '''simple docstring'''


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




class 					_lowerCAmelCase  (	lowercase   ):







 """simple docstring"""







 @staticmethod
 def 					_lowercase (			UpperCAmelCase__							:			ArgumentParser	):
    __lowercase								=						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=UpperCAmelCase__,					help="Configuration file on which to run."	)
    add_new_model_parser.add_argument(
        "--path",					type=UpperCAmelCase__,					help="Path to cookiecutter. Should only be used for testing purposes."	)
    add_new_model_parser.set_defaults(func=UpperCAmelCase__	)


 def __init__(			self							:			Tuple,					UpperCAmelCase__							:			bool,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Optional[Any]=None,					*UpperCAmelCase__							:			Union[str, Any]	):
    __lowercase								=						testing
    __lowercase								=						testing_file
    __lowercase								=						path



 def 					_lowercase (			self							:			Any	):
    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
    __lowercase								=						[directory for directory in os.listdir() if "cookiecutter-template-" == directory[:2_2]]
    if len(UpperCAmelCase__	) > 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."	)

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

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

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

    __lowercase								=						[directory for directory in os.listdir() if "cookiecutter-template-" in directory[:2_2]][0]

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

    __lowercase								=						configuration["lowercase_modelname"]
    __lowercase								=						configuration["generate_tensorflow_pytorch_and_flax"]
    os.remove(F"""{directory}/configuration.json"""	)

    __lowercase								=						"PyTorch" in generate_tensorflow_pytorch_and_flax
    __lowercase								=						"TensorFlow" in generate_tensorflow_pytorch_and_flax
    __lowercase								=						"Flax" in generate_tensorflow_pytorch_and_flax

    __lowercase								=						F"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}"""
    os.makedirs(UpperCAmelCase__,					exist_ok=UpperCAmelCase__	)
    os.makedirs(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}""",					exist_ok=UpperCAmelCase__	)

    # 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(UpperCAmelCase__							:			int	):
       with open(UpperCAmelCase__,					"r"	) as f:
          __lowercase								=						f.readlines()
       with open(UpperCAmelCase__,					"w"	) as f:
          for line in lines:
             if "# Copied from transformers." not in line:
                f.write(UpperCAmelCase__	)

    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(UpperCAmelCase__							:			str,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			List[str]	):
       # Create temp file
       __lowercase		,__lowercase								=						mkstemp()
       __lowercase								=						False
       with fdopen(UpperCAmelCase__,					"w"	) as new_file:
          with open(UpperCAmelCase__	) as old_file:
             for line in old_file:
                new_file.write(UpperCAmelCase__	)
                if line_to_copy_below in line:
                   __lowercase								=						True
                   for line_to_copy in lines_to_copy:
                      new_file.write(UpperCAmelCase__	)

       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(UpperCAmelCase__,					UpperCAmelCase__	)
       # Remove original file
       remove(UpperCAmelCase__	)
       # Move new file
       move(UpperCAmelCase__,					UpperCAmelCase__	)

    def skip_units(UpperCAmelCase__							:			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(UpperCAmelCase__							:			Optional[Any]	):
       with open(UpperCAmelCase__	) as datafile:
          __lowercase								=						[]
          __lowercase								=						False
          __lowercase								=						False
          for line in datafile:
             if "# To replace in: " in line and "##" not in line:
                __lowercase								=						line.split("\""	)[1]
                __lowercase								=						skip_units(UpperCAmelCase__	)
             elif "# Below: " in line and "##" not in line:
                __lowercase								=						line.split("\""	)[1]
                __lowercase								=						skip_units(UpperCAmelCase__	)
             elif "# End." in line and "##" not in line:
                if not skip_file and not skip_snippet:
                   replace(UpperCAmelCase__,					UpperCAmelCase__,					UpperCAmelCase__	)

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

       remove(UpperCAmelCase__	)

    replace_in_files(F"""{directory}/to_replace_{lowercase_model_name}.py"""	)
    os.rmdir(UpperCAmelCase__	)







"""simple docstring"""





from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a       =							logging.get_logger(__name__)

_a       =							{
    'huggingface/time-series-transformer-tourism-monthly': (
        'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}




class 					_lowerCAmelCase  (	lowercase   ):







 """simple docstring"""







 __UpperCAmelCase	:					int   		=	"time_series_transformer"
 __UpperCAmelCase	:					Any   		=	{
     "hidden_size": "d_model",
     "num_attention_heads": "encoder_attention_heads",
     "num_hidden_layers": "encoder_layers",
 }


 def __init__(			self							:			int,					UpperCAmelCase__							:			Optional[int] = None,					UpperCAmelCase__							:			Optional[int] = None,					UpperCAmelCase__							:			str = "student_t",					UpperCAmelCase__							:			str = "nll",					UpperCAmelCase__							:			int = 1,					UpperCAmelCase__							:			List[int] = [1, 2, 3, 4, 5, 6, 7],					UpperCAmelCase__							:			Optional[Union[str, bool]] = "mean",					UpperCAmelCase__							:			int = 0,					UpperCAmelCase__							:			int = 0,					UpperCAmelCase__							:			int = 0,					UpperCAmelCase__							:			int = 0,					UpperCAmelCase__							:			Optional[List[int]] = None,					UpperCAmelCase__							:			Optional[List[int]] = None,					UpperCAmelCase__							:			int = 3_2,					UpperCAmelCase__							:			int = 3_2,					UpperCAmelCase__							:			int = 2,					UpperCAmelCase__							:			int = 2,					UpperCAmelCase__							:			int = 2,					UpperCAmelCase__							:			int = 2,					UpperCAmelCase__							:			bool = True,					UpperCAmelCase__							:			str = "gelu",					UpperCAmelCase__							:			int = 6_4,					UpperCAmelCase__							:			float = 0.1,					UpperCAmelCase__							:			float = 0.1,					UpperCAmelCase__							:			float = 0.1,					UpperCAmelCase__							:			float = 0.1,					UpperCAmelCase__							:			float = 0.1,					UpperCAmelCase__							:			int = 1_0_0,					UpperCAmelCase__							:			float = 0.02,					UpperCAmelCase__							:			Any=True,					**UpperCAmelCase__							:			List[str],					):
    # time series specific configuration
    __lowercase								=						prediction_length
    __lowercase								=						context_length or prediction_length
    __lowercase								=						distribution_output
    __lowercase								=						loss
    __lowercase								=						input_size
    __lowercase								=						num_time_features
    __lowercase								=						lags_sequence
    __lowercase								=						scaling
    __lowercase								=						num_dynamic_real_features
    __lowercase								=						num_static_real_features
    __lowercase								=						num_static_categorical_features
    if cardinality and num_static_categorical_features > 0:
       if len(UpperCAmelCase__	) != num_static_categorical_features:
          raise ValueError(
              "The cardinality should be a list of the same length as `num_static_categorical_features`"	)
       __lowercase								=						cardinality
    else:
       __lowercase								=						[0]
    if embedding_dimension and num_static_categorical_features > 0:
       if len(UpperCAmelCase__	) != num_static_categorical_features:
          raise ValueError(
              "The embedding dimension should be a list of the same length as `num_static_categorical_features`"	)
       __lowercase								=						embedding_dimension
    else:
       __lowercase								=						[min(5_0,					(cat + 1) // 2	) for cat in self.cardinality]
    __lowercase								=						num_parallel_samples

    # Transformer architecture configuration
    __lowercase								=						input_size * len(UpperCAmelCase__	) + self._number_of_features
    __lowercase								=						d_model
    __lowercase								=						encoder_attention_heads
    __lowercase								=						decoder_attention_heads
    __lowercase								=						encoder_ffn_dim
    __lowercase								=						decoder_ffn_dim
    __lowercase								=						encoder_layers
    __lowercase								=						decoder_layers

    __lowercase								=						dropout
    __lowercase								=						attention_dropout
    __lowercase								=						activation_dropout
    __lowercase								=						encoder_layerdrop
    __lowercase								=						decoder_layerdrop

    __lowercase								=						activation_function
    __lowercase								=						init_std

    __lowercase								=						use_cache

    super().__init__(is_encoder_decoder=UpperCAmelCase__,					**UpperCAmelCase__	)



 @property
 def 					_lowercase (			self							:			Optional[Any]	):
    return (
        sum(self.embedding_dimension	)
        + self.num_dynamic_real_features
        + self.num_time_features
        + self.num_static_real_features
        + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
    )




