


import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test







class      lowerCAmelCase__       (				unittest.TestCase):




     '''simple docstring'''


     @parameterized.expand([(None,), ("foo.json",)])
     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				List[str]:
            _A      :       str				    = GenerationConfig(
                do_sample=__lowerCamelCase ,						temperature=0.7 ,						length_penalty=1.0 ,						bad_words_ids=[[1, 2, 3], [4, 5]] ,						)
            with tempfile.TemporaryDirectory() as tmp_dir:
                   config.save_pretrained(__lowerCamelCase ,						config_name=__lowerCamelCase)
                   _A      :       Tuple				    = GenerationConfig.from_pretrained(__lowerCamelCase ,						config_name=__lowerCamelCase)

            # Checks parameters that were specified
            self.assertEqual(loaded_config.do_sample ,						__lowerCamelCase)
            self.assertEqual(loaded_config.temperature ,						0.7)
            self.assertEqual(loaded_config.length_penalty ,						1.0)
            self.assertEqual(loaded_config.bad_words_ids ,						[[1, 2, 3], [4, 5]])

            # Checks parameters that were not specified (defaults)
            self.assertEqual(loaded_config.top_k ,						5_0)
            self.assertEqual(loaded_config.max_length ,						2_0)
            self.assertEqual(loaded_config.max_time ,						__lowerCamelCase)


     def  _lowerCamelCase (						self)			->				Optional[int]:
            _A      :       Optional[int]				    = AutoConfig.from_pretrained("gpt2")
            _A      :       int				    = GenerationConfig.from_model_config(__lowerCamelCase)
            _A      :       List[Any]				    = GenerationConfig()

            # The generation config has loaded a few non-default parameters from the model config
            self.assertNotEqual(__lowerCamelCase ,						__lowerCamelCase)

            # One of those parameters is eos_token_id -- check if it matches
            self.assertNotEqual(generation_config_from_model.eos_token_id ,						default_generation_config.eos_token_id)
            self.assertEqual(generation_config_from_model.eos_token_id ,						model_config.eos_token_id)


     def  _lowerCamelCase (						self)			->				Optional[Any]:
            _A      :       Optional[Any]				    = GenerationConfig()
            _A      :       List[Any]				    = {
                "max_new_tokens": 1_0_2_4,
                "foo": "bar",
            }
            _A      :       List[str]				    = copy.deepcopy(__lowerCamelCase)
            _A      :       int				    = generation_config.update(**__lowerCamelCase)

            # update_kwargs was not modified (no side effects)
            self.assertEqual(__lowerCamelCase ,						__lowerCamelCase)

            # update_kwargs was used to update the config on valid attributes
            self.assertEqual(generation_config.max_new_tokens ,						1_0_2_4)

            # `.update()` returns a dictionary of unused kwargs
            self.assertEqual(__lowerCamelCase ,						{"foo": "bar"})


     def  _lowerCamelCase (						self)			->				Any:
            _A      :       int				    = GenerationConfig()
            _A      :       int				    = "bar"

            with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
                   generation_config.save_pretrained(__lowerCamelCase)

                   _A      :       Any				    = GenerationConfig.from_pretrained(__lowerCamelCase)
            # update_kwargs was used to update the config on valid attributes
            self.assertEqual(new_config.foo ,						"bar")

            _A      :       Optional[Any]				    = GenerationConfig.from_model_config(__lowerCamelCase)
            assert not hasattr(__lowerCamelCase ,						"foo")  # no new kwargs should be initialized if from config


     def  _lowerCamelCase (						self)			->				List[str]:
            _A      :       Union[str, Any]				    = GenerationConfig()
            self.assertEqual(default_config.temperature ,						1.0)
            self.assertEqual(default_config.do_sample ,						__lowerCamelCase)
            self.assertEqual(default_config.num_beams ,						1)

            _A      :       Optional[int]				    = GenerationConfig(
                do_sample=__lowerCamelCase ,						temperature=0.7 ,						length_penalty=1.0 ,						bad_words_ids=[[1, 2, 3], [4, 5]] ,						)
            self.assertEqual(config.temperature ,						0.7)
            self.assertEqual(config.do_sample ,						__lowerCamelCase)
            self.assertEqual(config.num_beams ,						1)

            with tempfile.TemporaryDirectory() as tmp_dir:
                   config.save_pretrained(__lowerCamelCase)
                   _A      :       Optional[int]				    = GenerationConfig.from_pretrained(__lowerCamelCase ,						temperature=1.0)

            self.assertEqual(loaded_config.temperature ,						1.0)
            self.assertEqual(loaded_config.do_sample ,						__lowerCamelCase)
            self.assertEqual(loaded_config.num_beams ,						1)  # default value







@is_staging_test
class      lowerCAmelCase__       (				unittest.TestCase):




     '''simple docstring'''


     @classmethod
     def  _lowerCamelCase (						cls)			->				Optional[int]:
            _A      :       Dict				    = TOKEN
            HfFolder.save_token(__lowerCamelCase)


     @classmethod
     def  _lowerCamelCase (						cls)			->				List[Any]:
            try:
                   delete_repo(token=cls._token ,						repo_id="test-generation-config")
            except HTTPError:
                   pass

            try:
                   delete_repo(token=cls._token ,						repo_id="valid_org/test-generation-config-org")
            except HTTPError:
                   pass


     def  _lowerCamelCase (						self)			->				Any:
            _A      :       Optional[int]				    = GenerationConfig(
                do_sample=__lowerCamelCase ,						temperature=0.7 ,						length_penalty=1.0 ,						)
            config.push_to_hub("test-generation-config" ,						use_auth_token=self._token)

            _A      :       Union[str, Any]				    = GenerationConfig.from_pretrained(F"{USER}/test-generation-config")
            for k, v in config.to_dict().items():
                   if k != "transformers_version":
                          self.assertEqual(__lowerCamelCase ,						getattr(__lowerCamelCase ,						__lowerCamelCase))

        # Reset repo
            delete_repo(token=self._token ,						repo_id="test-generation-config")

            # Push to hub via save_pretrained
            with tempfile.TemporaryDirectory() as tmp_dir:
                   config.save_pretrained(
                       __lowerCamelCase ,						repo_id="test-generation-config" ,						push_to_hub=__lowerCamelCase ,						use_auth_token=self._token)

            _A      :       Optional[Any]				    = GenerationConfig.from_pretrained(F"{USER}/test-generation-config")
            for k, v in config.to_dict().items():
                   if k != "transformers_version":
                          self.assertEqual(__lowerCamelCase ,						getattr(__lowerCamelCase ,						__lowerCamelCase))


     def  _lowerCamelCase (						self)			->				Union[str, Any]:
            _A      :       Union[str, Any]				    = GenerationConfig(
                do_sample=__lowerCamelCase ,						temperature=0.7 ,						length_penalty=1.0 ,						)
            config.push_to_hub("valid_org/test-generation-config-org" ,						use_auth_token=self._token)

            _A      :       int				    = GenerationConfig.from_pretrained("valid_org/test-generation-config-org")
            for k, v in config.to_dict().items():
                   if k != "transformers_version":
                          self.assertEqual(__lowerCamelCase ,						getattr(__lowerCamelCase ,						__lowerCamelCase))

        # Reset repo
            delete_repo(token=self._token ,						repo_id="valid_org/test-generation-config-org")

            # Push to hub via save_pretrained
            with tempfile.TemporaryDirectory() as tmp_dir:
                   config.save_pretrained(
                       __lowerCamelCase ,						repo_id="valid_org/test-generation-config-org" ,						push_to_hub=__lowerCamelCase ,						use_auth_token=self._token)

            _A      :       Optional[int]				    = GenerationConfig.from_pretrained("valid_org/test-generation-config-org")
            for k, v in config.to_dict().items():
                   if k != "transformers_version":
                          self.assertEqual(__lowerCamelCase ,						getattr(__lowerCamelCase ,						__lowerCamelCase))




# flake8: noqa
# Lint as: python3

from typing import Dict, List, Optional, Type

from .. import config
from ..utils import logging
from .formatting import (
    ArrowFormatter,
    CustomFormatter,
    Formatter,
    PandasFormatter,
    PythonFormatter,
    TensorFormatter,
    format_table,
    query_table,
)
from .np_formatter import NumpyFormatter


lowerCAmelCase__      		= logging.get_logger(__name__)

lowerCAmelCase__      		= {}
lowerCAmelCase__      		= {}
lowerCAmelCase__      		= {}
def 							_UpperCAmelCase				(UpperCamelCase__     :  type				,							UpperCamelCase__     :  Optional[str]				,							UpperCamelCase__     :  Optional[List[str]] = None				,							):
       _A      :       Union[str, Any]				    = aliases if aliases is not None else []
       if format_type in _FORMAT_TYPES:
              logger.warning(
                  f"Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})"						)
       _A      :       Dict				    = formatter_cls
       for alias in set(aliases + [format_type]						):
              if alias in _FORMAT_TYPES_ALIASES:
                     logger.warning(
                         f"Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})"						)
              _A      :       Dict				    = format_type
def 							_UpperCAmelCase				(UpperCamelCase__     :  Exception				,							UpperCamelCase__     :  Optional[str]				,							UpperCamelCase__     :  Optional[List[str]] = None						):
       _A      :       Union[str, Any]				    = aliases if aliases is not None else []
       for alias in set(aliases + [format_type]						):
              _A      :       Union[str, Any]				    = unavailable_error


# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['python'])
_register_formatter(ArrowFormatter, 'arrow', aliases=['pa', 'pyarrow'])
_register_formatter(NumpyFormatter, 'numpy', aliases=['np'])
_register_formatter(PandasFormatter, 'pandas', aliases=['pd'])
_register_formatter(CustomFormatter, 'custom')

if config.TORCH_AVAILABLE:
    from .torch_formatter import TorchFormatter

    _register_formatter(TorchFormatter, 'torch', aliases=['pt', 'pytorch'])
else:
    lowerCAmelCase__      		= ValueError('PyTorch needs to be installed to be able to return PyTorch tensors.')
    _register_unavailable_formatter(_torch_error, 'torch', aliases=['pt', 'pytorch'])

if config.TF_AVAILABLE:
    from .tf_formatter import TFFormatter

    _register_formatter(TFFormatter, 'tensorflow', aliases=['tf'])
else:
    lowerCAmelCase__      		= ValueError('Tensorflow needs to be installed to be able to return Tensorflow tensors.')
    _register_unavailable_formatter(_tf_error, 'tensorflow', aliases=['tf'])

if config.JAX_AVAILABLE:
    from .jax_formatter import JaxFormatter

    _register_formatter(JaxFormatter, 'jax', aliases=[])
else:
    lowerCAmelCase__      		= ValueError('JAX needs to be installed to be able to return JAX arrays.')
    _register_unavailable_formatter(_jax_error, 'jax', aliases=[])
def 							_UpperCAmelCase				(UpperCamelCase__     :  Optional[str]						):
       if format_type in _FORMAT_TYPES_ALIASES:
              return _FORMAT_TYPES_ALIASES[format_type]
       else:
              return format_type






def 							_UpperCAmelCase				(UpperCamelCase__     :  Optional[str]				,							**UpperCamelCase__     :  List[Any]						):
       _A      :       List[str]				    = get_format_type_from_alias(UpperCamelCase__						)
       if format_type in _FORMAT_TYPES:
              return _FORMAT_TYPES[format_type](**UpperCamelCase__						)
       if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
              raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
       else:
              raise ValueError(
                  f"Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None						)}, but got '{format_type}'"						)
