

'''simple docstring'''

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 	A_			(    unittest.TestCase							):






     '''simple docstring'''



     @parameterized.expand([(None,), ('foo.json',)]	)
     def        UpperCAmelCase_	(		self			:					int					,      lowercase_			:					int	)						->     Dict:
      UpperCAmelCase	:     Dict						 =			GenerationConfig(
          do_sample=lowercase_					,      temperature=0.7					,      length_penalty=1.0					,      bad_words_ids=[[1, 2, 3], [4, 5]]					,      )
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(lowercase_					,      config_name=lowercase_	)
       UpperCAmelCase	:     Optional[int]						 =			GenerationConfig.from_pretrained(lowercase_					,      config_name=lowercase_	)

      # Checks parameters that were specified
      self.assertEqual(loaded_config.do_sample					,      lowercase_	)
      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					,      50	)
      self.assertEqual(loaded_config.max_length					,      20	)
      self.assertEqual(loaded_config.max_time					,      lowercase_	)


     def        UpperCAmelCase_	(		self			:					Any	)						->     Dict:
      UpperCAmelCase	:     Tuple						 =			AutoConfig.from_pretrained('gpt2'	)
      UpperCAmelCase	:     Any						 =			GenerationConfig.from_model_config(lowercase_	)
      UpperCAmelCase	:     List[Any]						 =			GenerationConfig()

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

      # 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        UpperCAmelCase_	(		self			:					int	)						->     Any:
      UpperCAmelCase	:     Optional[Any]						 =			GenerationConfig()
      UpperCAmelCase	:     Optional[Any]						 =			{
          'max_new_tokens': 1_024,
          'foo': 'bar',
      }
      UpperCAmelCase	:     Tuple						 =			copy.deepcopy(lowercase_	)
      UpperCAmelCase	:     int						 =			generation_config.update(**lowercase_	)

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

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

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


     def        UpperCAmelCase_	(		self			:					Any	)						->     Any:
      UpperCAmelCase	:     List[Any]						 =			GenerationConfig()
      UpperCAmelCase	:     str						 =			'bar'

      with tempfile.TemporaryDirectory('test-generation-config'	) as tmp_dir:
       generation_config.save_pretrained(lowercase_	)

       UpperCAmelCase	:     str						 =			GenerationConfig.from_pretrained(lowercase_	)
      # update_kwargs was used to update the config on valid attributes
      self.assertEqual(new_config.foo					,      'bar'	)

      UpperCAmelCase	:     Tuple						 =			GenerationConfig.from_model_config(lowercase_	)
      assert not hasattr(lowercase_					,      'foo'	)  # no new kwargs should be initialized if from config




     def        UpperCAmelCase_	(		self			:					Optional[Any]	)						->     Optional[int]:
      UpperCAmelCase	:     Dict						 =			GenerationConfig()
      self.assertEqual(default_config.temperature					,      1.0	)
      self.assertEqual(default_config.do_sample					,      lowercase_	)
      self.assertEqual(default_config.num_beams					,      1	)

      UpperCAmelCase	:     Any						 =			GenerationConfig(
          do_sample=lowercase_					,      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					,      lowercase_	)
      self.assertEqual(config.num_beams					,      1	)

      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(lowercase_	)
       UpperCAmelCase	:     Optional[Any]						 =			GenerationConfig.from_pretrained(lowercase_					,      temperature=1.0	)

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




@is_staging_test
class 	A_			(    unittest.TestCase							):






     '''simple docstring'''



     @classmethod
     def        UpperCAmelCase_	(		cls			:					Dict	)						->     Union[str, Any]:
      UpperCAmelCase	:     int						 =			TOKEN
      HfFolder.save_token(lowercase_	)


     @classmethod
     def        UpperCAmelCase_	(		cls			:					int	)						->     int:
      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        UpperCAmelCase_	(		self			:					List[Any]	)						->     Any:
      UpperCAmelCase	:     Optional[int]						 =			GenerationConfig(
          do_sample=lowercase_					,      temperature=0.7					,      length_penalty=1.0					,      )
      config.push_to_hub('test-generation-config'					,      use_auth_token=self._token	)

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

        # 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(
           lowercase_					,      repo_id='test-generation-config'					,      push_to_hub=lowercase_					,      use_auth_token=self._token	)

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




     def        UpperCAmelCase_	(		self			:					List[str]	)						->     Union[str, Any]:
      UpperCAmelCase	:     Tuple						 =			GenerationConfig(
          do_sample=lowercase_					,      temperature=0.7					,      length_penalty=1.0					,      )
      config.push_to_hub('valid_org/test-generation-config-org'					,      use_auth_token=self._token	)

      UpperCAmelCase	:     List[Any]						 =			GenerationConfig.from_pretrained('valid_org/test-generation-config-org'	)
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(lowercase_					,      getattr(lowercase_					,      lowercase_	)	)

        # 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(
           lowercase_					,      repo_id='valid_org/test-generation-config-org'					,      push_to_hub=lowercase_					,      use_auth_token=self._token	)

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







'''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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


lowercase__         =      logging.get_logger(__name__)




def 				UpperCamelCase(					UpperCAmelCase_  ,	UpperCAmelCase_     ):
 UpperCAmelCase	:     Optional[Any]						 =			b.T
 UpperCAmelCase	:     Optional[int]						 =			np.sum(np.square(UpperCAmelCase_     )  ,	axis=1     )
 UpperCAmelCase	:     List[Any]						 =			np.sum(np.square(UpperCAmelCase_     )  ,	axis=0     )
 UpperCAmelCase	:     List[str]						 =			np.matmul(UpperCAmelCase_  ,	UpperCAmelCase_     )
 UpperCAmelCase	:     Union[str, Any]						 =			aa[:, None] - 2 * ab + ba[None, :]
 return d




def 				UpperCamelCase(					UpperCAmelCase_  ,	UpperCAmelCase_     ):
 UpperCAmelCase	:     int						 =			x.reshape(-1  ,	3     )
 UpperCAmelCase	:     Optional[int]						 =			squared_euclidean_distance(UpperCAmelCase_  ,	UpperCAmelCase_     )
 return np.argmin(UpperCAmelCase_  ,	axis=1     )




class 	A_			(    _snake_case							):






     '''simple docstring'''



     UpperCAmelCase_						:     List[Any]  		=  ["""pixel_values"""]


     def __init__(		self			:					List[Any]					,      lowercase_			:					Optional[Union[List[List[int]], np.ndarray]] = None					,      lowercase_			:					bool = True					,      lowercase_			:					Dict[str, int] = None					,      lowercase_			:					PILImageResampling = PILImageResampling.BILINEAR					,      lowercase_			:					bool = True					,      lowercase_			:					bool = True					,      **lowercase_			:					Optional[Any]					,      )						->     None:
      super().__init__(**lowercase_	)
      UpperCAmelCase	:     Any						 =			size if size is not None else {'height': 256, 'width': 256}
      UpperCAmelCase	:     List[Any]						 =			get_size_dict(lowercase_	)
      UpperCAmelCase	:     str						 =			np.array(lowercase_	) if clusters is not None else None
      UpperCAmelCase	:     Any						 =			do_resize
      UpperCAmelCase	:     List[Any]						 =			size
      UpperCAmelCase	:     Any						 =			resample
      UpperCAmelCase	:     Dict						 =			do_normalize
      UpperCAmelCase	:     List[Any]						 =			do_color_quantize


     def        UpperCAmelCase_	(		self			:					int					,      lowercase_			:					np.ndarray					,      lowercase_			:					Dict[str, int]					,      lowercase_			:					PILImageResampling = PILImageResampling.BILINEAR					,      lowercase_			:					Optional[Union[str, ChannelDimension]] = None					,      **lowercase_			:					Any					,      )						->     np.ndarray:
      UpperCAmelCase	:     Dict						 =			get_size_dict(lowercase_	)
      if "height" not in size or "width" not in size:
       raise ValueError(f"""Size dictionary must contain both height and width keys. Got {size.keys()}"""	)
      return resize(
          lowercase_					,      size=(size['height'], size['width'])					,      resample=lowercase_					,      data_format=lowercase_					,      **lowercase_	)


     def        UpperCAmelCase_	(		self			:					Optional[int]					,      lowercase_			:					np.ndarray					,      lowercase_			:					Optional[Union[str, ChannelDimension]] = None					,      )						->     np.ndarray:
      UpperCAmelCase	:     int						 =			rescale(image=lowercase_					,      scale=1 / 127.5					,      data_format=lowercase_	)
      UpperCAmelCase	:     Dict						 =			image - 1
      return image




     def        UpperCAmelCase_	(		self			:					str					,      lowercase_			:					ImageInput					,      lowercase_			:					bool = None					,      lowercase_			:					Dict[str, int] = None					,      lowercase_			:					PILImageResampling = None					,      lowercase_			:					bool = None					,      lowercase_			:					Optional[bool] = None					,      lowercase_			:					Optional[Union[List[List[int]], np.ndarray]] = None					,      lowercase_			:					Optional[Union[str, TensorType]] = None					,      lowercase_			:					Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST					,      **lowercase_			:					List[str]					,      )						->     PIL.Image.Image:
      UpperCAmelCase	:     Optional[int]						 =			do_resize if do_resize is not None else self.do_resize
      UpperCAmelCase	:     Optional[Any]						 =			size if size is not None else self.size
      UpperCAmelCase	:     Optional[int]						 =			get_size_dict(lowercase_	)
      UpperCAmelCase	:     Any						 =			resample if resample is not None else self.resample
      UpperCAmelCase	:     Optional[Any]						 =			do_normalize if do_normalize is not None else self.do_normalize
      UpperCAmelCase	:     str						 =			do_color_quantize if do_color_quantize is not None else self.do_color_quantize
      UpperCAmelCase	:     Optional[int]						 =			clusters if clusters is not None else self.clusters
      UpperCAmelCase	:     List[str]						 =			np.array(lowercase_	)

      UpperCAmelCase	:     int						 =			make_list_of_images(lowercase_	)

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

      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_color_quantize and clusters is None:
       raise ValueError('Clusters must be specified if do_color_quantize is True.'	)

      # All transformations expect numpy arrays.
      UpperCAmelCase	:     Dict						 =			[to_numpy_array(lowercase_	) for image in images]

      if do_resize:
       UpperCAmelCase	:     List[Any]						 =			[self.resize(image=lowercase_					,      size=lowercase_					,      resample=lowercase_	) for image in images]

      if do_normalize:
       UpperCAmelCase	:     Tuple						 =			[self.normalize(image=lowercase_	) for image in images]

      if do_color_quantize:
       UpperCAmelCase	:     List[str]						 =			[to_channel_dimension_format(lowercase_					,      ChannelDimension.LAST	) for image in images]
       # color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
       UpperCAmelCase	:     int						 =			np.array(lowercase_	)
       UpperCAmelCase	:     str						 =			color_quantize(lowercase_					,      lowercase_	).reshape(images.shape[:-1]	)

       # flatten to (batch_size, height*width)
       UpperCAmelCase	:     Optional[int]						 =			images.shape[0]
       UpperCAmelCase	:     Union[str, Any]						 =			images.reshape(lowercase_					,      -1	)

       # We need to convert back to a list of images to keep consistent behaviour across processors.
       UpperCAmelCase	:     int						 =			list(lowercase_	)
      else:
       UpperCAmelCase	:     Dict						 =			[to_channel_dimension_format(lowercase_					,      lowercase_	) for image in images]

      UpperCAmelCase	:     Any						 =			{'input_ids': images}
      return BatchFeature(data=lowercase_					,      tensor_type=lowercase_	)




