

'''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,
    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					 =	logging.get_logger(__name__)


if is_vision_available():
       import PIL


class 	lowerCAmelCase  (   A ):
       lowerCAmelCase_												=			["pixel_values"]







       def __init__(				self      :			Dict    ,   __lowercase      :			bool = True    ,   __lowercase      :			Dict[str, int] = None    ,   __lowercase      :			PILImageResampling = PILImageResampling.BICUBIC    ,   __lowercase      :			bool = True    ,   __lowercase      :			Dict[str, int] = None    ,   __lowercase      :			bool = True    ,   __lowercase      :			Union[int, float] = 1 / 255    ,   __lowercase      :			bool = True    ,   __lowercase      :			Optional[Union[float, List[float]]] = None    ,   __lowercase      :			Optional[Union[float, List[float]]] = None    ,   __lowercase      :			bool = True    ,   **__lowercase      :			Tuple    ,   ):







            """simple docstring"""







            super().__init__(**__lowercase   )
            __lowercase      		=size if size is not None else {'shortest_edge': 224}
            __lowercase      		=get_size_dict(__lowercase    ,   default_to_square=__lowercase   )
            __lowercase      		=crop_size if crop_size is not None else {'height': 224, 'width': 224}
            __lowercase      		=get_size_dict(__lowercase    ,   default_to_square=__lowercase    ,   param_name='crop_size'   )

            __lowercase      		=do_resize
            __lowercase      		=size
            __lowercase      		=resample
            __lowercase      		=do_center_crop
            __lowercase      		=crop_size
            __lowercase      		=do_rescale
            __lowercase      		=rescale_factor
            __lowercase      		=do_normalize
            __lowercase      		=image_mean if image_mean is not None else OPENAI_CLIP_MEAN
            __lowercase      		=image_std if image_std is not None else OPENAI_CLIP_STD
            __lowercase      		=do_convert_rgb







       def       snake_case (				self      :			Optional[Any]    ,   __lowercase      :			np.ndarray    ,   __lowercase      :			Dict[str, int]    ,   __lowercase      :			PILImageResampling = PILImageResampling.BICUBIC    ,   __lowercase      :			Optional[Union[str, ChannelDimension]] = None    ,   **__lowercase      :			List[Any]    ,   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Union[str, Any]    ,   __lowercase      :			np.ndarray    ,   __lowercase      :			Dict[str, int]    ,   __lowercase      :			Optional[Union[str, ChannelDimension]] = None    ,   **__lowercase      :			List[str]    ,   ):







            """simple docstring"""







            __lowercase      		=get_size_dict(__lowercase   )
            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(__lowercase    ,   size=(size['height'], size['width'])    ,   data_format=__lowercase    ,   **__lowercase   )







       def       snake_case (				self      :			Any    ,   __lowercase      :			np.ndarray    ,   __lowercase      :			Union[int, float]    ,   __lowercase      :			Optional[Union[str, ChannelDimension]] = None    ,   **__lowercase      :			List[str]    ,   ):







            """simple docstring"""







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







       def       snake_case (				self      :			List[Any]    ,   __lowercase      :			np.ndarray    ,   __lowercase      :			Union[float, List[float]]    ,   __lowercase      :			Union[float, List[float]]    ,   __lowercase      :			Optional[Union[str, ChannelDimension]] = None    ,   **__lowercase      :			Optional[Any]    ,   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Optional[Any]    ,   __lowercase      :			ImageInput    ,   __lowercase      :			bool = None    ,   __lowercase      :			Dict[str, int] = None    ,   __lowercase      :			PILImageResampling = None    ,   __lowercase      :			bool = None    ,   __lowercase      :			int = None    ,   __lowercase      :			bool = None    ,   __lowercase      :			float = None    ,   __lowercase      :			bool = None    ,   __lowercase      :			Optional[Union[float, List[float]]] = None    ,   __lowercase      :			Optional[Union[float, List[float]]] = None    ,   __lowercase      :			bool = None    ,   __lowercase      :			Optional[Union[str, TensorType]] = None    ,   __lowercase      :			Optional[ChannelDimension] = ChannelDimension.FIRST    ,   **__lowercase      :			List[Any]    ,   ):







            """simple docstring"""







            __lowercase      		=do_resize if do_resize is not None else self.do_resize
            __lowercase      		=size if size is not None else self.size
            __lowercase      		=get_size_dict(__lowercase    ,   param_name='size'    ,   default_to_square=__lowercase   )
            __lowercase      		=resample if resample is not None else self.resample
            __lowercase      		=do_center_crop if do_center_crop is not None else self.do_center_crop
            __lowercase      		=crop_size if crop_size is not None else self.crop_size
            __lowercase      		=get_size_dict(__lowercase    ,   param_name='crop_size'    ,   default_to_square=__lowercase   )
            __lowercase      		=do_rescale if do_rescale is not None else self.do_rescale
            __lowercase      		=rescale_factor if rescale_factor is not None else self.rescale_factor
            __lowercase      		=do_normalize if do_normalize is not None else self.do_normalize
            __lowercase      		=image_mean if image_mean is not None else self.image_mean
            __lowercase      		=image_std if image_std is not None else self.image_std
            __lowercase      		=do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

            __lowercase      		=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:
                 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:
                 __lowercase      		=[convert_to_rgb(__lowercase   ) for image in images]

            # All transformations expect numpy arrays.
            __lowercase      		=[to_numpy_array(__lowercase   ) for image in images]

            if do_resize:
                 __lowercase      		=[self.resize(image=__lowercase    ,   size=__lowercase    ,   resample=__lowercase   ) for image in images]

            if do_center_crop:
                 __lowercase      		=[self.center_crop(image=__lowercase    ,   size=__lowercase   ) for image in images]

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

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

            __lowercase      		=[to_channel_dimension_format(__lowercase    ,   __lowercase   ) for image in images]

            __lowercase      		={'pixel_values': images}
            return BatchFeature(data=__lowercase    ,   tensor_type=__lowercase   )





'''simple docstring'''

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					 =	get_tests_dir('''fixtures''')


class 	lowerCAmelCase  (   unittest.TestCase ):







       def       snake_case (				self      :			str   ):







            """simple docstring"""







            __lowercase      		=mock.Mock()
            __lowercase      		=500
            __lowercase      		={}
            __lowercase      		=HTTPError
            __lowercase      		={}

            # Download this model to make sure it's in the cache.
            __lowercase      		=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=__lowercase   ) as mock_head:
                 __lowercase      		=WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2'   )
                 # This check we did call the fake head request
                 mock_head.assert_called()







       def       snake_case (				self      :			Dict   ):







            """simple docstring"""







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






@is_staging_test
class 	lowerCAmelCase  (   unittest.TestCase ):







       @classmethod
       def       snake_case (				cls      :			str   ):







            """simple docstring"""







            __lowercase      		=TOKEN
            HfFolder.save_token(__lowercase   )







       @classmethod
       def       snake_case (				cls      :			str   ):







            """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       snake_case (				self      :			int   ):







            """simple docstring"""







            __lowercase      		=WavaVecaFeatureExtractor.from_pretrained(__lowercase   )
            feature_extractor.push_to_hub('test-feature-extractor'    ,   use_auth_token=self._token   )

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

            # 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(
                     __lowercase    ,   repo_id='test-feature-extractor'    ,   push_to_hub=__lowercase    ,   use_auth_token=self._token   )

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







       def       snake_case (				self      :			List[Any]   ):







            """simple docstring"""







            __lowercase      		=WavaVecaFeatureExtractor.from_pretrained(__lowercase   )
            feature_extractor.push_to_hub('valid_org/test-feature-extractor'    ,   use_auth_token=self._token   )

            __lowercase      		=WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor'   )
            for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__lowercase    ,   getattr(__lowercase    ,   __lowercase   )   )

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

            __lowercase      		=WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org'   )
            for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__lowercase    ,   getattr(__lowercase    ,   __lowercase   )   )







       def       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







            CustomFeatureExtractor.register_for_auto_class()
            __lowercase      		=CustomFeatureExtractor.from_pretrained(__lowercase   )

            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'}    ,   )

            __lowercase      		=AutoFeatureExtractor.from_pretrained(
                f'''{USER}/test-dynamic-feature-extractor'''    ,   trust_remote_code=__lowercase   )
            # 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'   )


