




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


_snake_case				:				List[str]       							=		logging.get_logger(__name__)

class       A   (		SCREAMING_SNAKE_CASE__   ):
							lowercase_          =    ['pixel_values']







							def __init__(  self	:  int							,      lowerCAmelCase_	:  bool = True							,      lowerCAmelCase_	:  Optional[Dict[str, int]] = None							,      lowerCAmelCase_	:  PILImageResampling = PILImageResampling.BILINEAR							,      lowerCAmelCase_	:  bool = True							,      lowerCAmelCase_	:  Dict[str, int] = None							,      lowerCAmelCase_	:  bool = True							,      lowerCAmelCase_	:  Union[int, float] = 1 / 2_55							,      lowerCAmelCase_	:  bool = True							,      lowerCAmelCase_	:  Optional[Union[float, List[float]]] = None							,      lowerCAmelCase_	:  Optional[Union[float, List[float]]] = None							,      **lowerCAmelCase_	:  Dict							,      )      ->							List[str]:


														"""simple docstring"""


														super().__init__(**a_ )
														_a     					=    size if size is not None else {'''shortest_edge''': 2_56}
														_a     					=    get_size_dict(a_							,      default_to_square=a_ )
														_a     					=    crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
														_a     					=    get_size_dict(a_ )
														_a     					=    do_resize
														_a     					=    size
														_a     					=    resample
														_a     					=    do_center_crop
														_a     					=    crop_size
														_a     					=    do_rescale
														_a     					=    rescale_factor
														_a     					=    do_normalize
														_a     					=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
														_a     					=    image_std if image_std is not None else IMAGENET_STANDARD_STD







							def        __lowerCAmelCase      (  self	:  str							,      lowerCAmelCase_	:  np.ndarray							,      lowerCAmelCase_	:  Dict[str, int]							,      lowerCAmelCase_	:  PILImageResampling = PILImageResampling.BICUBIC							,      lowerCAmelCase_	:  Optional[Union[str, ChannelDimension]] = None							,      **lowerCAmelCase_	:  int							,      )      ->							Dict:


														"""simple docstring"""


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







							def        __lowerCAmelCase      (  self	:  List[Any]							,      lowerCAmelCase_	:  np.ndarray							,      lowerCAmelCase_	:  Dict[str, int]							,      lowerCAmelCase_	:  Optional[Union[str, ChannelDimension]] = None							,      **lowerCAmelCase_	:  List[str]							,      )      ->							Optional[int]:


														"""simple docstring"""


														_a     					=    get_size_dict(a_ )
														return center_crop(a_							,      size=(size['''height'''], size['''width'''])							,      data_format=a_							,      **a_ )







							def        __lowerCAmelCase      (  self	:  List[Any]							,      lowerCAmelCase_	:  np.ndarray							,      lowerCAmelCase_	:  float							,      lowerCAmelCase_	:  Optional[Union[str, ChannelDimension]] = None							,      **lowerCAmelCase_	:  List[Any] )      ->							Optional[int]:


														"""simple docstring"""


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







							def        __lowerCAmelCase      (  self	:  Optional[Any]							,      lowerCAmelCase_	:  np.ndarray							,      lowerCAmelCase_	:  Union[float, List[float]]							,      lowerCAmelCase_	:  Union[float, List[float]]							,      lowerCAmelCase_	:  Optional[Union[str, ChannelDimension]] = None							,      **lowerCAmelCase_	:  Any							,      )      ->							Any:


														"""simple docstring"""


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







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


														"""simple docstring"""


														_a     					=    do_resize if do_resize is not None else self.do_resize
														_a     					=    size if size is not None else self.size
														_a     					=    get_size_dict(a_							,      default_to_square=a_ )
														_a     					=    resample if resample is not None else self.resample
														_a     					=    do_center_crop if do_center_crop is not None else self.do_center_crop
														_a     					=    crop_size if crop_size is not None else self.crop_size
														_a     					=    get_size_dict(a_ )
														_a     					=    do_rescale if do_rescale is not None else self.do_rescale
														_a     					=    rescale_factor if rescale_factor is not None else self.rescale_factor
														_a     					=    do_normalize if do_normalize is not None else self.do_normalize
														_a     					=    image_mean if image_mean is not None else self.image_mean
														_a     					=    image_std if image_std is not None else self.image_std

														_a     					=    make_list_of_images(a_ )

														if not valid_images(a_ ):
																					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.''' )

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

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

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

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

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

														_a     					=    [to_channel_dimension_format(a_							,      a_ ) for image in images]

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







'''simple docstring'''


import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


_snake_case				:				int       							=		get_tests_dir('fixtures')
_snake_case				:				Tuple       							=		get_tests_dir('fixtures/dummy_feature_extractor_config.json')
_snake_case				:				Optional[int]       							=		get_tests_dir('fixtures/dummy-config.json')

class       A   (		unittest.TestCase   ):







							def        __lowerCAmelCase      (  self	:  int )      ->							List[Any]:


														"""simple docstring"""


														_a     					=    0







							def        __lowerCAmelCase      (  self	:  List[str] )      ->							int:


														"""simple docstring"""


														_a     					=    AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''' )
														self.assertIsInstance(lowerCAmelCase_							,      lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  str )      ->							Tuple:


														"""simple docstring"""


														_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
														self.assertIsInstance(lowerCAmelCase_							,      lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  List[str] )      ->							Any:


														"""simple docstring"""


														with tempfile.TemporaryDirectory() as tmpdirname:
																					_a     					=    WavaVecaConfig()

																					# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
																					_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ ).to_dict()

																					config_dict.pop('''feature_extractor_type''' )
																					_a     					=    WavaVecaFeatureExtractor(**lowerCAmelCase_ )

																					# save in new folder
																					model_config.save_pretrained(lowerCAmelCase_ )
																					config.save_pretrained(lowerCAmelCase_ )

																					_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )

																					# make sure private variable is not incorrectly saved
																					_a     					=    json.loads(config.to_json_string() )
																					self.assertTrue('''_processor_class''' not in dict_as_saved )

														self.assertIsInstance(lowerCAmelCase_							,      lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							Optional[Any]:


														"""simple docstring"""


														_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
														self.assertIsInstance(lowerCAmelCase_							,      lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  Optional[int] )      ->							str:


														"""simple docstring"""


														with self.assertRaisesRegex(
														    lowerCAmelCase_							,      '''bert-base is not a local folder and is not a valid model identifier''' ):
																					_a     					=    AutoFeatureExtractor.from_pretrained('''bert-base''' )







							def        __lowerCAmelCase      (  self	:  Tuple )      ->							Union[str, Any]:


														"""simple docstring"""


														with self.assertRaisesRegex(
														    lowerCAmelCase_							,      R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
																					_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_							,      revision='''aaaaaa''' )







							def        __lowerCAmelCase      (  self	:  Any )      ->							Dict:


														"""simple docstring"""


														with self.assertRaisesRegex(
														    lowerCAmelCase_							,      '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''							,      ):
																					_a     					=    AutoFeatureExtractor.from_pretrained('''hf-internal-testing/config-no-model''' )







							def        __lowerCAmelCase      (  self	:  List[Any] )      ->							Any:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    AutoFeatureExtractor.from_pretrained(
																					    '''hf-internal-testing/test_dynamic_feature_extractor''' )
														# If remote code is disabled, we can't load this config.
														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    AutoFeatureExtractor.from_pretrained(
																					    '''hf-internal-testing/test_dynamic_feature_extractor'''							,      trust_remote_code=lowerCAmelCase_ )

														_a     					=    AutoFeatureExtractor.from_pretrained(
														    '''hf-internal-testing/test_dynamic_feature_extractor'''							,      trust_remote_code=lowerCAmelCase_ )
														self.assertEqual(feature_extractor.__class__.__name__							,      '''NewFeatureExtractor''' )

														# Test feature extractor can be reloaded.
														with tempfile.TemporaryDirectory() as tmp_dir:
																					feature_extractor.save_pretrained(lowerCAmelCase_ )
																					_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_							,      trust_remote_code=lowerCAmelCase_ )
														self.assertEqual(reloaded_feature_extractor.__class__.__name__							,      '''NewFeatureExtractor''' )







							def        __lowerCAmelCase      (  self	:  int )      ->							Optional[Any]:


														"""simple docstring"""


														try:
																					AutoConfig.register('''custom'''							,      lowerCAmelCase_ )
																					AutoFeatureExtractor.register(lowerCAmelCase_							,      lowerCAmelCase_ )
																					# Trying to register something existing in the Transformers library will raise an error
																					with self.assertRaises(lowerCAmelCase_ ):
																												AutoFeatureExtractor.register(lowerCAmelCase_							,      lowerCAmelCase_ )

																					# Now that the config is registered, it can be used as any other config with the auto-API
																					_a     					=    CustomFeatureExtractor.from_pretrained(lowerCAmelCase_ )
																					with tempfile.TemporaryDirectory() as tmp_dir:
																												feature_extractor.save_pretrained(lowerCAmelCase_ )
																												_a     					=    AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
																												self.assertIsInstance(lowerCAmelCase_							,      lowerCAmelCase_ )

														finally:
																					if "custom" in CONFIG_MAPPING._extra_content:
																												del CONFIG_MAPPING._extra_content["custom"]
																					if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																												del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







							def        __lowerCAmelCase      (  self	:  Optional[int] )      ->							Any:


														"""simple docstring"""


														class       A   (		_a   ):
																					lowercase_          =    True

														try:
																					AutoConfig.register('''custom'''							,      lowerCAmelCase_ )
																					AutoFeatureExtractor.register(lowerCAmelCase_							,      lowerCAmelCase_ )
																					# If remote code is not set, the default is to use local
																					_a     					=    AutoFeatureExtractor.from_pretrained(
																					    '''hf-internal-testing/test_dynamic_feature_extractor''' )
																					self.assertEqual(feature_extractor.__class__.__name__							,      '''NewFeatureExtractor''' )
																					self.assertTrue(feature_extractor.is_local )

																					# If remote code is disabled, we load the local one.
																					_a     					=    AutoFeatureExtractor.from_pretrained(
																					    '''hf-internal-testing/test_dynamic_feature_extractor'''							,      trust_remote_code=lowerCAmelCase_ )
																					self.assertEqual(feature_extractor.__class__.__name__							,      '''NewFeatureExtractor''' )
																					self.assertTrue(feature_extractor.is_local )

																					# If remote is enabled, we load from the Hub
																					_a     					=    AutoFeatureExtractor.from_pretrained(
																					    '''hf-internal-testing/test_dynamic_feature_extractor'''							,      trust_remote_code=lowerCAmelCase_ )
																					self.assertEqual(feature_extractor.__class__.__name__							,      '''NewFeatureExtractor''' )
																					self.assertTrue(not hasattr(lowerCAmelCase_							,      '''is_local''' ) )

														finally:
																					if "custom" in CONFIG_MAPPING._extra_content:
																												del CONFIG_MAPPING._extra_content["custom"]
																					if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																												del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]

