




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


_lowerCamelCase			:	Optional[int]							 =     get_tests_dir("""fixtures""")
_lowerCamelCase			:	List[str]							 =     get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_lowerCamelCase			:	Union[str, Any]							 =     get_tests_dir("""fixtures/dummy-config.json""")


class        UpperCamelCase_					(				unittest.TestCase  ):

    '''simple docstring'''






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





           '''simple docstring'''

           A__   				=					0


    def  SCREAMING_SNAKE_CASE							(    self   :			List[str])		->str:





           '''simple docstring'''

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


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[Any])		->Union[str, Any]:





           '''simple docstring'''

           A__   				=					AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)
           self.assertIsInstance(UpperCAmelCase__      ,				UpperCAmelCase__)


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





           '''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(UpperCAmelCase__).to_dict()

                  config_dict.pop('''feature_extractor_type''')
                  A__   				=					WavaVecaFeatureExtractor(**UpperCAmelCase__)

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

                  A__   				=					AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)

                  # 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(UpperCAmelCase__      ,				UpperCAmelCase__)


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





           '''simple docstring'''

           A__   				=					AutoFeatureExtractor.from_pretrained(UpperCAmelCase__)
           self.assertIsInstance(UpperCAmelCase__      ,				UpperCAmelCase__)


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





           '''simple docstring'''

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


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





           '''simple docstring'''

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


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[Any])		->List[Any]:





           '''simple docstring'''

           with self.assertRaisesRegex(
               UpperCAmelCase__      ,				'''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  SCREAMING_SNAKE_CASE							(    self   :			List[Any])		->Union[str, Any]:





           '''simple docstring'''

           with self.assertRaises(UpperCAmelCase__):
                  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(UpperCAmelCase__):
                  A__   				=					AutoFeatureExtractor.from_pretrained(
                      '''hf-internal-testing/test_dynamic_feature_extractor'''      ,				trust_remote_code=UpperCAmelCase__)

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

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


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int])		->Dict:





           '''simple docstring'''

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

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

           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  SCREAMING_SNAKE_CASE							(    self   :			int)		->Optional[int]:





           '''simple docstring'''

           class        UpperCamelCase_					(				__UpperCAmelCase  ):

               '''simple docstring'''






               UpperCAmelCase__													=   True

           try:
                  AutoConfig.register('''custom'''      ,				UpperCAmelCase__)
                  AutoFeatureExtractor.register(UpperCAmelCase__      ,				UpperCAmelCase__)
                  # 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=UpperCAmelCase__)
                  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=UpperCAmelCase__)
                  self.assertEqual(feature_extractor.__class__.__name__      ,				'''NewFeatureExtractor''')
                  self.assertTrue(not hasattr(UpperCAmelCase__      ,				'''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]








from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase			:	str							 =     logging.get_logger(__name__)


class        UpperCamelCase_					(				UpperCAmelCase__  ):

    '''simple docstring'''






    UpperCAmelCase__													=   ['''pixel_values''']


    def __init__(    self   :			List[Any]      ,				UpperCAmelCase__   :			bool = True      ,				UpperCAmelCase__   :			int = 32      ,				UpperCAmelCase__   :			Dict=PILImageResampling.BILINEAR      ,				UpperCAmelCase__   :			bool = True      ,				**UpperCAmelCase__   :			Optional[int]      ,				)		->None:





           '''simple docstring'''

           A__   				=					do_resize
           A__   				=					do_rescale
           A__   				=					size_divisor
           A__   				=					resample
           super().__init__(**UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			int      ,				UpperCAmelCase__   :			np.ndarray      ,				UpperCAmelCase__   :			int      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			Optional[ChannelDimension] = None      ,				**UpperCAmelCase__   :			Dict)		->np.ndarray:





           '''simple docstring'''

           A__				,							A__   				=					get_image_size(UpperCAmelCase__)
           # Rounds the height and width down to the closest multiple of size_divisor
           A__   				=					height // size_divisor * size_divisor
           A__   				=					width // size_divisor * size_divisor
           A__   				=					resize(UpperCAmelCase__      ,				(new_h, new_w)      ,				resample=UpperCAmelCase__      ,				data_format=UpperCAmelCase__      ,				**UpperCAmelCase__)
           return image


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





           '''simple docstring'''

           return rescale(image=UpperCAmelCase__      ,				scale=UpperCAmelCase__      ,				data_format=UpperCAmelCase__      ,				**UpperCAmelCase__)





    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int]      ,				UpperCAmelCase__   :			Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]]      ,				UpperCAmelCase__   :			Optional[bool] = None      ,				UpperCAmelCase__   :			Optional[int] = None      ,				UpperCAmelCase__   :			Dict=None      ,				UpperCAmelCase__   :			Optional[bool] = None      ,				UpperCAmelCase__   :			Optional[Union[TensorType, str]] = None      ,				UpperCAmelCase__   :			ChannelDimension = ChannelDimension.FIRST      ,				**UpperCAmelCase__   :			List[str]      ,				)		->BatchFeature:





           '''simple docstring'''

           A__   				=					do_resize if do_resize is not None else self.do_resize
           A__   				=					do_rescale if do_rescale is not None else self.do_rescale
           A__   				=					size_divisor if size_divisor is not None else self.size_divisor
           A__   				=					resample if resample is not None else self.resample

           if do_resize and size_divisor is None:
                  raise ValueError('''size_divisor is required for resizing''')

           A__   				=					make_list_of_images(UpperCAmelCase__)

           if not valid_images(UpperCAmelCase__):
                  raise ValueError('''Invalid image(s)''')

           # All transformations expect numpy arrays.
           A__   				=					[to_numpy_array(UpperCAmelCase__) for img in images]

           if do_resize:
                  A__   				=					[self.resize(UpperCAmelCase__      ,				size_divisor=UpperCAmelCase__      ,				resample=UpperCAmelCase__) for image in images]

           if do_rescale:
                  A__   				=					[self.rescale(UpperCAmelCase__      ,				scale=1 / 255) for image in images]

           A__   				=					[to_channel_dimension_format(UpperCAmelCase__      ,				UpperCAmelCase__) for image in images]

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


