



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       :	List[str]            =get_tests_dir('fixtures')
__snake_case       :	Optional[int]            =get_tests_dir('fixtures/dummy_feature_extractor_config.json')
__snake_case       :	Any            =get_tests_dir('fixtures/dummy-config.json')



class  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



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

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  0



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

						"""simple docstring"""






						lowerCAmelCase__  :       str				=  AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h'''				)
						self.assertIsInstance(__lowerCamelCase	,__lowerCamelCase				)



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase				)
						self.assertIsInstance(__lowerCamelCase	,__lowerCamelCase				)



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

						"""simple docstring"""






						with tempfile.TemporaryDirectory() as tmpdirname:
										lowerCAmelCase__  :       Any				=  WavaVecaConfig()

										# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
										lowerCAmelCase__  :       int				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase				).to_dict()

										config_dict.pop('''feature_extractor_type'''				)
										lowerCAmelCase__  :       Tuple				=  WavaVecaFeatureExtractor(**__lowerCamelCase				)

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

										lowerCAmelCase__  :       Union[str, Any]				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase				)

										# make sure private variable is not incorrectly saved
										lowerCAmelCase__  :       List[str]				=  json.loads(config.to_json_string()				)
										self.assertTrue('''_processor_class''' not in dict_as_saved				)

						self.assertIsInstance(__lowerCamelCase	,__lowerCamelCase				)



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

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase				)
						self.assertIsInstance(__lowerCamelCase	,__lowerCamelCase				)



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

						"""simple docstring"""






						with self.assertRaisesRegex(
						    __lowerCamelCase	,'''bert-base is not a local folder and is not a valid model identifier'''				):
										lowerCAmelCase__  :       List[str]				=  AutoFeatureExtractor.from_pretrained('''bert-base'''				)



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






						with self.assertRaisesRegex(
						    __lowerCamelCase	,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''				):
										lowerCAmelCase__  :       List[Any]				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase	,revision='''aaaaaa'''				)



		def 	lowerCAmelCase__   (self				)  ->    str:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    int:

						"""simple docstring"""






						with self.assertRaises(__lowerCamelCase				):
										lowerCAmelCase__  :       List[Any]				=  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				):
										lowerCAmelCase__  :       Any				=  AutoFeatureExtractor.from_pretrained(
										    '''hf-internal-testing/test_dynamic_feature_extractor'''	,trust_remote_code=__lowerCamelCase				)

						lowerCAmelCase__  :       int				=  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				)
										lowerCAmelCase__  :       Optional[int]				=  AutoFeatureExtractor.from_pretrained(__lowerCamelCase	,trust_remote_code=__lowerCamelCase				)
						self.assertEqual(reloaded_feature_extractor.__class__.__name__	,'''NewFeatureExtractor'''				)



		def 	lowerCAmelCase__   (self				)  ->    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
										lowerCAmelCase__  :       Optional[Any]				=  CustomFeatureExtractor.from_pretrained(__lowerCamelCase				)
										with tempfile.TemporaryDirectory() as tmp_dir:
														feature_extractor.save_pretrained(__lowerCamelCase				)
														lowerCAmelCase__  :       List[Any]				=  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				)  ->    str:

						"""simple docstring"""






						class  lowerCamelCase__    (							lowerCamelCase__):




								'''simple docstring'''



								snake_case_			=True

						try:
										AutoConfig.register('''custom'''	,__lowerCamelCase				)
										AutoFeatureExtractor.register(__lowerCamelCase	,__lowerCamelCase				)
										# If remote code is not set, the default is to use local
										lowerCAmelCase__  :       Union[str, Any]				=  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.
										lowerCAmelCase__  :       List[str]				=  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
										lowerCAmelCase__  :       Any				=  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]






from typing import Dict, List, Optional, Tuple, 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, is_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


__snake_case       :	List[Any]            =logging.get_logger(__name__)



class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_			=["""pixel_values"""]



		def __init__(self	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = PILImageResampling.BILINEAR	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = True	,__lowerCamelCase = 1 / 2_55	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    None:

						"""simple docstring"""






						super().__init__(**__lowerCamelCase				)
						lowerCAmelCase__  :       List[Any]				=  size if size is not None else {'''shortest_edge''': 2_56}
						lowerCAmelCase__  :       Any				=  get_size_dict(__lowerCamelCase	,default_to_square=__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
						lowerCAmelCase__  :       Any				=  get_size_dict(__lowerCamelCase	,param_name='''crop_size'''				)
						lowerCAmelCase__  :       Dict				=  do_resize
						lowerCAmelCase__  :       str				=  size
						lowerCAmelCase__  :       Tuple				=  resample
						lowerCAmelCase__  :       List[Any]				=  do_center_crop
						lowerCAmelCase__  :       Dict				=  crop_size
						lowerCAmelCase__  :       Optional[int]				=  do_rescale
						lowerCAmelCase__  :       List[str]				=  rescale_factor
						lowerCAmelCase__  :       List[Any]				=  do_normalize
						lowerCAmelCase__  :       Optional[Any]				=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCAmelCase__  :       str				=  image_std if image_std is not None else IMAGENET_STANDARD_STD



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = PILImageResampling.BICUBIC	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  get_size_dict(__lowerCamelCase				)
						if "height" not in size or "width" not in size:
										raise ValueError(f"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"""				)
						return center_crop(__lowerCamelCase	,size=(size['''height'''], size['''width'''])	,data_format=__lowerCamelCase	,**__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase				)  ->    np.ndarray:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = ChannelDimension.FIRST	,**__lowerCamelCase	,)  ->    Optional[Any]:

						"""simple docstring"""






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

						lowerCAmelCase__  :       Any				=  make_list_of_images(__lowerCamelCase				)

						if not valid_images(__lowerCamelCase				):
										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.
						lowerCAmelCase__  :       Union[str, Any]				=  [to_numpy_array(__lowerCamelCase				) for image in images]

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

						if do_center_crop:
										lowerCAmelCase__  :       List[Any]				=  [self.center_crop(image=__lowerCamelCase	,size=__lowerCamelCase				) for image in images]

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

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

						lowerCAmelCase__  :       int				=  [to_channel_dimension_format(__lowerCamelCase	,__lowerCamelCase				) for image in images]

						lowerCAmelCase__  :       int				=  {'''pixel_values''': images}
						return BatchFeature(data=__lowerCamelCase	,tensor_type=__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase = None				)  ->    Union[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  outputs.logits

						# Resize logits and compute semantic segmentation maps
						if target_sizes is not None:
										if len(__lowerCamelCase				) != len(__lowerCamelCase				):
														raise ValueError(
														    '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

										if is_torch_tensor(__lowerCamelCase				):
														lowerCAmelCase__  :       str				=  target_sizes.numpy()

										lowerCAmelCase__  :       Optional[Any]				=  []

										for idx in range(len(__lowerCamelCase				)				):
														lowerCAmelCase__  :       Optional[int]				=  torch.nn.functional.interpolate(
														    logits[idx].unsqueeze(dim=0				)	,size=target_sizes[idx]	,mode='''bilinear'''	,align_corners=__lowerCamelCase				)
														lowerCAmelCase__  :       Optional[Any]				=  resized_logits[0].argmax(dim=0				)
														semantic_segmentation.append(__lowerCamelCase				)
						else:
										lowerCAmelCase__  :       Optional[Any]				=  logits.argmax(dim=1				)
										lowerCAmelCase__  :       int				=  [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

						return semantic_segmentation

