

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


UpperCAmelCase__ :     Dict				    =    logging.get_logger(__name__)


if is_vision_available():
  import PIL







class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : List[str]			       =["""pixel_values"""]


  def __init__(			self    : Tuple				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : PILImageResampling = PILImageResampling.BICUBIC				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Union[int, float] = 1 / 2_5_5				,				UpperCAmelCase__    : bool = True				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : Optional[Union[float, List[float]]] = None				,				UpperCAmelCase__    : bool = True				,				**UpperCAmelCase__    : Union[str, Any]				,				)					->None:
        """simple docstring"""







        super().__init__(**UpperCamelCase_		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   size if size is not None else {'shortest_edge': 2_2_4}
        SCREAMING_SNAKE_CASE :      str       =   get_size_dict(UpperCamelCase_				,				default_to_square=UpperCamelCase_		)
        SCREAMING_SNAKE_CASE :      List[str]       =   crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   get_size_dict(UpperCamelCase_				,				default_to_square=UpperCamelCase_				,				param_name="""crop_size"""		)

        SCREAMING_SNAKE_CASE :      List[str]       =   do_resize
        SCREAMING_SNAKE_CASE :      int       =   size
        SCREAMING_SNAKE_CASE :      int       =   resample
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   do_center_crop
        SCREAMING_SNAKE_CASE :      Optional[int]       =   crop_size
        SCREAMING_SNAKE_CASE :      Optional[int]       =   do_rescale
        SCREAMING_SNAKE_CASE :      List[str]       =   rescale_factor
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   do_normalize
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   image_mean if image_mean is not None else OPENAI_CLIP_MEAN
        SCREAMING_SNAKE_CASE :      Any       =   image_std if image_std is not None else OPENAI_CLIP_STD
        SCREAMING_SNAKE_CASE :      List[Any]       =   do_convert_rgb


  def  _lowercase      (			self    : List[Any]				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Dict[str, int]				,				UpperCAmelCase__    : PILImageResampling = PILImageResampling.BICUBIC				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : int				,				)					->np.ndarray:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   get_size_dict(UpperCamelCase_				,				default_to_square=UpperCamelCase_		)
        if "shortest_edge" not in size:
              raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   get_resize_output_image_size(UpperCamelCase_				,				size=size["""shortest_edge"""]				,				default_to_square=UpperCamelCase_		)
        return resize(UpperCamelCase_				,				size=UpperCamelCase_				,				resample=UpperCamelCase_				,				data_format=UpperCamelCase_				,				**UpperCamelCase_		)


  def  _lowercase      (			self    : int				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Dict[str, int]				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : Optional[int]				,				)					->np.ndarray:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[Any]       =   get_size_dict(UpperCamelCase_		)
        if "height" not in size or "width" not in size:
              raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}"		)
        return center_crop(UpperCamelCase_				,				size=(size["""height"""], size["""width"""])				,				data_format=UpperCamelCase_				,				**UpperCamelCase_		)


  def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Union[int, float]				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : int				,				)					->List[str]:
        """simple docstring"""







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


  def  _lowercase      (			self    : str				,				UpperCAmelCase__    : np.ndarray				,				UpperCAmelCase__    : Union[float, List[float]]				,				UpperCAmelCase__    : Union[float, List[float]]				,				UpperCAmelCase__    : Optional[Union[str, ChannelDimension]] = None				,				**UpperCAmelCase__    : Optional[int]				,				)					->np.ndarray:
        """simple docstring"""







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




  def  _lowercase      (			self    : int				,				UpperCAmelCase__    : ImageInput				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : Dict[str, int] = None				,				UpperCAmelCase__    : PILImageResampling = None				,				UpperCAmelCase__    : bool = None				,				UpperCAmelCase__    : 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__    : bool = None				,				UpperCAmelCase__    : Optional[Union[str, TensorType]] = None				,				UpperCAmelCase__    : Optional[ChannelDimension] = ChannelDimension.FIRST				,				**UpperCAmelCase__    : Optional[int]				,				)					->PIL.Image.Image:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   do_resize if do_resize is not None else self.do_resize
        SCREAMING_SNAKE_CASE :      Tuple       =   size if size is not None else self.size
        SCREAMING_SNAKE_CASE :      Tuple       =   get_size_dict(UpperCamelCase_				,				param_name="""size"""				,				default_to_square=UpperCamelCase_		)
        SCREAMING_SNAKE_CASE :      Dict       =   resample if resample is not None else self.resample
        SCREAMING_SNAKE_CASE :      Dict       =   do_center_crop if do_center_crop is not None else self.do_center_crop
        SCREAMING_SNAKE_CASE :      List[Any]       =   crop_size if crop_size is not None else self.crop_size
        SCREAMING_SNAKE_CASE :      Optional[int]       =   get_size_dict(UpperCamelCase_				,				param_name="""crop_size"""				,				default_to_square=UpperCamelCase_		)
        SCREAMING_SNAKE_CASE :      Any       =   do_rescale if do_rescale is not None else self.do_rescale
        SCREAMING_SNAKE_CASE :      Tuple       =   rescale_factor if rescale_factor is not None else self.rescale_factor
        SCREAMING_SNAKE_CASE :      Any       =   do_normalize if do_normalize is not None else self.do_normalize
        SCREAMING_SNAKE_CASE :      Any       =   image_mean if image_mean is not None else self.image_mean
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   image_std if image_std is not None else self.image_std
        SCREAMING_SNAKE_CASE :      Optional[int]       =   do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        SCREAMING_SNAKE_CASE :      int       =   make_list_of_images(UpperCamelCase_		)

        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."""		)

        if do_resize and size is None:
              raise ValueError("""Size 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."""		)

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   [convert_to_rgb(UpperCamelCase_		) for image in images]

        # All transformations expect numpy arrays.
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   [to_numpy_array(UpperCamelCase_		) for image in images]

        if do_resize:
              SCREAMING_SNAKE_CASE :      List[str]       =   [self.resize(image=UpperCamelCase_				,				size=UpperCamelCase_				,				resample=UpperCamelCase_		) for image in images]

        if do_center_crop:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   [self.center_crop(image=UpperCamelCase_				,				size=UpperCamelCase_		) for image in images]

        if do_rescale:
              SCREAMING_SNAKE_CASE :      str       =   [self.rescale(image=UpperCamelCase_				,				scale=UpperCamelCase_		) for image in images]

        if do_normalize:
              SCREAMING_SNAKE_CASE :      Dict       =   [self.normalize(image=UpperCamelCase_				,				mean=UpperCamelCase_				,				std=UpperCamelCase_		) for image in images]

        SCREAMING_SNAKE_CASE :      List[str]       =   [to_channel_dimension_format(UpperCamelCase_				,				UpperCamelCase_		) for image in images]

        SCREAMING_SNAKE_CASE :      int       =   {'pixel_values': images}
        return BatchFeature(data=UpperCamelCase_				,				tensor_type=UpperCamelCase_		)







import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

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

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / """utils"""))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCAmelCase__ :     int				    =    get_tests_dir("""fixtures""")







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Dict		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   mock.Mock()
        SCREAMING_SNAKE_CASE :      Optional[int]       =   5_0_0
        SCREAMING_SNAKE_CASE :      List[str]       =   {}
        SCREAMING_SNAKE_CASE :      List[Any]       =   HTTPError
        SCREAMING_SNAKE_CASE :      int       =   {}

        # Download this model to make sure it's in the cache.
        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
        # Under the mock environment we get a 500 error when trying to reach the model.
        with mock.patch("""requests.Session.request"""				,				return_value=UpperCAmelCase__		) as mock_head:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""		)
              # This check we did call the fake head request
              mock_head.assert_called()




  def  _lowercase      (			self    : Optional[Any]		)					->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   WavaVecaFeatureExtractor.from_pretrained(
            """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"""		)







@is_staging_test
class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   TOKEN
        HfFolder.save_token(UpperCAmelCase__		)


  @classmethod
  def  _lowercase      (			cls    : List[str]		)					->Optional[int]:
        """simple docstring"""







        try:
              delete_repo(token=cls._token				,				repo_id="""test-feature-extractor"""		)
        except HTTPError:
              pass

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

        try:
              delete_repo(token=cls._token				,				repo_id="""test-dynamic-feature-extractor"""		)
        except HTTPError:
              pass


  def  _lowercase      (			self    : int		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Any       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

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

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  UpperCAmelCase__				,				repo_id="""test-feature-extractor"""				,				push_to_hub=UpperCAmelCase__				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)


  def  _lowercase      (			self    : List[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   WavaVecaFeatureExtractor.from_pretrained(UpperCAmelCase__		)
        feature_extractor.push_to_hub("""valid_org/test-feature-extractor"""				,				use_auth_token=self._token		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)

        # Reset repo
        delete_repo(token=self._token				,				repo_id="""valid_org/test-feature-extractor"""		)

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

        SCREAMING_SNAKE_CASE :      List[Any]       =   WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org"""		)
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(UpperCAmelCase__				,				getattr(UpperCAmelCase__				,				UpperCAmelCase__		)		)




  def  _lowercase      (			self    : Optional[Any]		)					->Optional[int]:
        """simple docstring"""







        CustomFeatureExtractor.register_for_auto_class()
        SCREAMING_SNAKE_CASE :      Any       =   CustomFeatureExtractor.from_pretrained(UpperCAmelCase__		)

        feature_extractor.push_to_hub("""test-dynamic-feature-extractor"""				,				use_auth_token=self._token		)

        # This has added the proper auto_map field to the config
        self.assertDictEqual(
            feature_extractor.auto_map				,				{"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""}				,				)

        SCREAMING_SNAKE_CASE :      Any       =   AutoFeatureExtractor.from_pretrained(
            f"{USER}/test-dynamic-feature-extractor"				,				trust_remote_code=UpperCAmelCase__		)
        # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
        self.assertEqual(new_feature_extractor.__class__.__name__				,				"""CustomFeatureExtractor"""		)




