import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate



class 			UpperCamelCase					(			__lowercase			):

     '''simple docstring'''

     A_					    =	CONFIG_NAME



     @register_to_config
     def __init__(       self					,					A_ = True					,					A_ = 8					,					A_ = "lanczos"					,					A_ = True					,					A_ = False					,					)			->					int:






           """simple docstring"""
           super().__init__()



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					PIL.Image.Image:






           """simple docstring"""
           if images.ndim == 3:
                 _lowerCamelCase           =					images[None, ...]
           _lowerCamelCase           =					(images * 2_55).round().astype('''uint8'''    )
           if images.shape[-1] == 1:
                 # special case for grayscale (single channel) images
                 _lowerCamelCase           =					[Image.fromarray(image.squeeze()					,					mode='''L'''    ) for image in images]
           else:
                 _lowerCamelCase           =					[Image.fromarray(A_    ) for image in images]

           return pil_images



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					np.ndarray:






           """simple docstring"""
           if not isinstance(A_					,					A_    ):
                 _lowerCamelCase           =					[images]
           _lowerCamelCase           =					[np.array(A_    ).astype(np.floataa    ) / 255.0 for image in images]
           _lowerCamelCase           =					np.stack(A_					,					axis=0    )

           return images



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					torch.FloatTensor:






           """simple docstring"""
           if images.ndim == 3:
                 _lowerCamelCase           =					images[..., None]

           _lowerCamelCase           =					torch.from_numpy(images.transpose(0					,					3					,					1					,					2    )    )
           return images



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					np.ndarray:






           """simple docstring"""
           _lowerCamelCase           =					images.cpu().permute(0					,					2					,					3					,					1    ).float().numpy()
           return images



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					Dict:






           """simple docstring"""
           return 2.0 * images - 1.0



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					Optional[int]:






           """simple docstring"""
           return (images / 2 + 0.5).clamp(0					,					1    )



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					PIL.Image.Image:






           """simple docstring"""
           _lowerCamelCase           =					image.convert('''RGB'''    )
           return image



     def 		UpperCamelCase_    (       self					,					A_					,					A_ = None					,					A_ = None					,					)			->					PIL.Image.Image:






           """simple docstring"""
           if height is None:
                 _lowerCamelCase           =					image.height
           if width is None:
                 _lowerCamelCase           =					image.width

           _lowerCamelCase     ,       _lowerCamelCase           =					(
               x - x % self.config.vae_scale_factor for x in (width, height)
           )  # resize to integer multiple of vae_scale_factor
           _lowerCamelCase           =					image.resize((width, height)					,					resample=PIL_INTERPOLATION[self.config.resample]    )
           return image



     def 		UpperCamelCase_    (       self					,					A_					,					A_ = None					,					A_ = None					,					)			->					torch.Tensor:






           """simple docstring"""
           _lowerCamelCase           =					(PIL.Image.Image, np.ndarray, torch.Tensor)
           if isinstance(A_					,					A_    ):
                 _lowerCamelCase           =					[image]
           elif not (isinstance(A_					,					A_    ) and all(isinstance(A_					,					A_    ) for i in image    )):
                 raise ValueError(
                     F'Input is in incorrect format: {[type(A_    ) for i in image]}. Currently, we only support {", ".join(A_    )}'    )

           if isinstance(image[0]					,					PIL.Image.Image    ):
                 if self.config.do_convert_rgb:
                       _lowerCamelCase           =					[self.convert_to_rgb(A_    ) for i in image]
                 if self.config.do_resize:
                       _lowerCamelCase           =					[self.resize(A_					,					A_					,					A_    ) for i in image]
                 _lowerCamelCase           =					self.pil_to_numpy(A_    )  # to np
                 _lowerCamelCase           =					self.numpy_to_pt(A_    )  # to pt

           elif isinstance(image[0]					,					np.ndarray    ):
                 _lowerCamelCase           =					np.concatenate(A_					,					axis=0    ) if image[0].ndim == 4 else np.stack(A_					,					axis=0    )
                 _lowerCamelCase           =					self.numpy_to_pt(A_    )
                 _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase           =					image.shape
                 if self.config.do_resize and (
                     height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                 ):
                       raise ValueError(
                           F'Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}'
                           F'currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'    )

           elif isinstance(image[0]					,					torch.Tensor    ):
                 _lowerCamelCase           =					torch.cat(A_					,					axis=0    ) if image[0].ndim == 4 else torch.stack(A_					,					axis=0    )
                 _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase     ,       _lowerCamelCase           =					image.shape

                 # don't need any preprocess if the image is latents
                 if channel == 4:
                       return image

                 if self.config.do_resize and (
                     height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                 ):
                       raise ValueError(
                           F'Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}'
                           F'currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'    )

        # expected range [0,1], normalize to [-1,1]
           _lowerCamelCase           =					self.config.do_normalize
           if image.min() < 0:
                 warnings.warn(
                     '''Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] '''
                     F'when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]'					,					A_					,					)
                 _lowerCamelCase           =					False

           if do_normalize:
                 _lowerCamelCase           =					self.normalize(A_    )

           return image





     def 		UpperCamelCase_    (       self					,					A_					,					A_ = "pil"					,					A_ = None					,					)			->					List[str]:






           """simple docstring"""
           if not isinstance(A_					,					torch.Tensor    ):
                 raise ValueError(
                     F'Input for postprocessing is in incorrect format: {type(A_    )}. We only support pytorch tensor'    )
           if output_type not in ["latent", "pt", "np", "pil"]:
                 _lowerCamelCase           =					(
                     F'the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '
                     '''`pil`, `np`, `pt`, `latent`'''
                 )
                 deprecate('''Unsupported output_type'''					,					'''1.0.0'''					,					A_					,					standard_warn=A_    )
                 _lowerCamelCase           =					'''np'''

           if output_type == "latent":
                 return image

           if do_denormalize is None:
                 _lowerCamelCase           =					[self.config.do_normalize] * image.shape[0]

           _lowerCamelCase           =					torch.stack(
               [self.denormalize(image[i]    ) if do_denormalize[i] else image[i] for i in range(image.shape[0]    )]    )

           if output_type == "pt":
                 return image

           _lowerCamelCase           =					self.pt_to_numpy(A_    )

           if output_type == "np":
                 return image

           if output_type == "pil":
                 return self.numpy_to_pil(A_    )





class 			UpperCamelCase					(			__lowercase			):

     '''simple docstring'''

     A_					    =	CONFIG_NAME



     @register_to_config
     def __init__(       self					,					A_ = True					,					A_ = 8					,					A_ = "lanczos"					,					A_ = True					,					)			->					str:






           """simple docstring"""
           super().__init__()



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					Any:






           """simple docstring"""
           if images.ndim == 3:
                 _lowerCamelCase           =					images[None, ...]
           _lowerCamelCase           =					(images * 2_55).round().astype('''uint8'''    )
           if images.shape[-1] == 1:
                 # special case for grayscale (single channel) images
                 _lowerCamelCase           =					[Image.fromarray(image.squeeze()					,					mode='''L'''    ) for image in images]
           else:
                 _lowerCamelCase           =					[Image.fromarray(image[:, :, :3]    ) for image in images]

           return pil_images



     @staticmethod
     def 		UpperCamelCase_    (       A_    )			->					List[str]:






           """simple docstring"""
           return image[:, :, 1] * 2**8 + image[:, :, 2]



     def 		UpperCamelCase_    (       self					,					A_    )			->					Optional[int]:






           """simple docstring"""
           if images.ndim == 3:
                 _lowerCamelCase           =					images[None, ...]
           _lowerCamelCase           =					images[:, :, :, 3:]
           if images.shape[-1] == 6:
                 _lowerCamelCase           =					(images_depth * 2_55).round().astype('''uint8'''    )
                 _lowerCamelCase           =					[
                     Image.fromarray(self.rgblike_to_depthmap(A_    )					,					mode='''I;16'''    ) for image_depth in images_depth
                 ]
           elif images.shape[-1] == 4:
                 _lowerCamelCase           =					(images_depth * 65535.0).astype(np.uintaa    )
                 _lowerCamelCase           =					[Image.fromarray(A_					,					mode='''I;16'''    ) for image_depth in images_depth]
           else:
                 raise Exception('''Not supported'''    )

           return pil_images





     def 		UpperCamelCase_    (       self					,					A_					,					A_ = "pil"					,					A_ = None					,					)			->					str:






           """simple docstring"""
           if not isinstance(A_					,					torch.Tensor    ):
                 raise ValueError(
                     F'Input for postprocessing is in incorrect format: {type(A_    )}. We only support pytorch tensor'    )
           if output_type not in ["latent", "pt", "np", "pil"]:
                 _lowerCamelCase           =					(
                     F'the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '
                     '''`pil`, `np`, `pt`, `latent`'''
                 )
                 deprecate('''Unsupported output_type'''					,					'''1.0.0'''					,					A_					,					standard_warn=A_    )
                 _lowerCamelCase           =					'''np'''

           if do_denormalize is None:
                 _lowerCamelCase           =					[self.config.do_normalize] * image.shape[0]

           _lowerCamelCase           =					torch.stack(
               [self.denormalize(image[i]    ) if do_denormalize[i] else image[i] for i in range(image.shape[0]    )]    )

           _lowerCamelCase           =					self.pt_to_numpy(A_    )

           if output_type == "np":
                 if image.shape[-1] == 6:
                       _lowerCamelCase           =					np.stack([self.rgblike_to_depthmap(im[:, :, 3:]    ) for im in image]					,					axis=0    )
                 else:
                       _lowerCamelCase           =					image[:, :, :, 3:]
                 return image[:, :, :, :3], image_depth

           if output_type == "pil":
                 return self.numpy_to_pil(A_    ), self.numpy_to_depth(A_    )
           else:
                 raise Exception(F'This type {output_type} is not supported'    )
import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


snake_case__						      =			logging.get_logger(__name__)

snake_case__						      =			OrderedDict(
    [
        ('align', 'AlignProcessor'),
        ('altclip', 'AltCLIPProcessor'),
        ('bark', 'BarkProcessor'),
        ('blip', 'BlipProcessor'),
        ('blip-2', 'Blip2Processor'),
        ('bridgetower', 'BridgeTowerProcessor'),
        ('chinese_clip', 'ChineseCLIPProcessor'),
        ('clap', 'ClapProcessor'),
        ('clip', 'CLIPProcessor'),
        ('clipseg', 'CLIPSegProcessor'),
        ('flava', 'FlavaProcessor'),
        ('git', 'GitProcessor'),
        ('groupvit', 'CLIPProcessor'),
        ('hubert', 'Wav2Vec2Processor'),
        ('instructblip', 'InstructBlipProcessor'),
        ('layoutlmv2', 'LayoutLMv2Processor'),
        ('layoutlmv3', 'LayoutLMv3Processor'),
        ('markuplm', 'MarkupLMProcessor'),
        ('mctct', 'MCTCTProcessor'),
        ('mgp-str', 'MgpstrProcessor'),
        ('oneformer', 'OneFormerProcessor'),
        ('owlvit', 'OwlViTProcessor'),
        ('pix2struct', 'Pix2StructProcessor'),
        ('sam', 'SamProcessor'),
        ('sew', 'Wav2Vec2Processor'),
        ('sew-d', 'Wav2Vec2Processor'),
        ('speech_to_text', 'Speech2TextProcessor'),
        ('speech_to_text_2', 'Speech2Text2Processor'),
        ('speecht5', 'SpeechT5Processor'),
        ('trocr', 'TrOCRProcessor'),
        ('tvlt', 'TvltProcessor'),
        ('unispeech', 'Wav2Vec2Processor'),
        ('unispeech-sat', 'Wav2Vec2Processor'),
        ('vilt', 'ViltProcessor'),
        ('vision-text-dual-encoder', 'VisionTextDualEncoderProcessor'),
        ('wav2vec2', 'Wav2Vec2Processor'),
        ('wav2vec2-conformer', 'Wav2Vec2Processor'),
        ('wavlm', 'Wav2Vec2Processor'),
        ('whisper', 'WhisperProcessor'),
        ('xclip', 'XCLIPProcessor'),
    ]
)

snake_case__						      =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
def    __magic_name__(	__UpperCAmelCase		)    ->     List[str]:



      '''simple docstring'''

      for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
            if class_name in processors:
                  _lowerCamelCase           =					model_type_to_module_name(__UpperCAmelCase		)

                  _lowerCamelCase           =					importlib.import_module(F'.{module_name}'			,    '''transformers.models'''		)
                  try:
                        return getattr(__UpperCAmelCase			,    __UpperCAmelCase		)
                  except AttributeError:
                        continue

      for processor in PROCESSOR_MAPPING._extra_content.values():
            if getattr(__UpperCAmelCase			,    '''__name__'''			,    __UpperCAmelCase		) == class_name:
                  return processor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
      _lowerCamelCase           =					importlib.import_module('''transformers'''		)
      if hasattr(__UpperCAmelCase			,    __UpperCAmelCase		):
            return getattr(__UpperCAmelCase			,    __UpperCAmelCase		)

      return None




class 			UpperCamelCase					:

     '''simple docstring'''

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






           """simple docstring"""
           raise EnvironmentError(
               '''AutoProcessor is designed to be instantiated '''
               '''using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method.'''    )



     @classmethod
     @replace_list_option_in_docstrings(A_    )
     def 		UpperCamelCase_    (       cls					,					A_					,					**A_    )			->					List[Any]:






           """simple docstring"""
           _lowerCamelCase           =					kwargs.pop('''config'''					,					A_    )
           _lowerCamelCase           =					kwargs.pop('''trust_remote_code'''					,					A_    )
           _lowerCamelCase           =					True

           _lowerCamelCase           =					None
           _lowerCamelCase           =					None

           # First, let's see if we have a preprocessor config.
           # Filter the kwargs for `get_file_from_repo`.
           _lowerCamelCase           =					{
               key: kwargs[key] for key in inspect.signature(A_    ).parameters.keys() if key in kwargs
           }
           # Let's start by checking whether the processor class is saved in an image processor
           _lowerCamelCase           =					get_file_from_repo(
               A_					,					A_					,					**A_    )
           if preprocessor_config_file is not None:
                 _lowerCamelCase     ,       _lowerCamelCase           =					ImageProcessingMixin.get_image_processor_dict(A_					,					**A_    )
                 _lowerCamelCase           =					config_dict.get('''processor_class'''					,					A_    )
                 if "AutoProcessor" in config_dict.get('''auto_map'''					,					{}    ):
                       _lowerCamelCase           =					config_dict['''auto_map''']['''AutoProcessor''']

        # If not found, let's check whether the processor class is saved in a feature extractor config
           if preprocessor_config_file is not None and processor_class is None:
                 _lowerCamelCase     ,       _lowerCamelCase           =					FeatureExtractionMixin.get_feature_extractor_dict(A_					,					**A_    )
                 _lowerCamelCase           =					config_dict.get('''processor_class'''					,					A_    )
                 if "AutoProcessor" in config_dict.get('''auto_map'''					,					{}    ):
                       _lowerCamelCase           =					config_dict['''auto_map''']['''AutoProcessor''']

           if processor_class is None:
                 # Next, let's check whether the processor class is saved in a tokenizer
                 _lowerCamelCase           =					get_file_from_repo(
                     A_					,					A_					,					**A_    )
                 if tokenizer_config_file is not None:
                       with open(A_					,					encoding='''utf-8'''    ) as reader:
                             _lowerCamelCase           =					json.load(A_    )

                       _lowerCamelCase           =					config_dict.get('''processor_class'''					,					A_    )
                       if "AutoProcessor" in config_dict.get('''auto_map'''					,					{}    ):
                             _lowerCamelCase           =					config_dict['''auto_map''']['''AutoProcessor''']

           if processor_class is None:
                 # Otherwise, load config, if it can be loaded.
                 if not isinstance(A_					,					A_    ):
                       _lowerCamelCase           =					AutoConfig.from_pretrained(
                           A_					,					trust_remote_code=A_					,					**A_    )

                 # And check if the config contains the processor class.
                 _lowerCamelCase           =					getattr(A_					,					'''processor_class'''					,					A_    )
                 if hasattr(A_					,					'''auto_map'''    ) and "AutoProcessor" in config.auto_map:
                       _lowerCamelCase           =					config.auto_map['''AutoProcessor''']

           if processor_class is not None:
                 _lowerCamelCase           =					processor_class_from_name(A_    )

           _lowerCamelCase           =					processor_auto_map is not None
           _lowerCamelCase           =					processor_class is not None or type(A_    ) in PROCESSOR_MAPPING
           _lowerCamelCase           =					resolve_trust_remote_code(
               A_					,					A_					,					A_					,					A_    )

           if has_remote_code and trust_remote_code:
                 _lowerCamelCase           =					get_class_from_dynamic_module(
                     A_					,					A_					,					**A_    )
                 _lowerCamelCase           =					kwargs.pop('''code_revision'''					,					A_    )
                 if os.path.isdir(A_    ):
                       processor_class.register_for_auto_class()
                 return processor_class.from_pretrained(
                     A_					,					trust_remote_code=A_					,					**A_    )
           elif processor_class is not None:
                 return processor_class.from_pretrained(
                     A_					,					trust_remote_code=A_					,					**A_    )
           # Last try: we use the PROCESSOR_MAPPING.
           elif type(A_    ) in PROCESSOR_MAPPING:
                 return PROCESSOR_MAPPING[type(A_    )].from_pretrained(A_					,					**A_    )

           # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
           # tokenizer.
           try:
                 return AutoTokenizer.from_pretrained(
                     A_					,					trust_remote_code=A_					,					**A_    )
           except Exception:
                 try:
                       return AutoImageProcessor.from_pretrained(
                           A_					,					trust_remote_code=A_					,					**A_    )
                 except Exception:
                       pass

                 try:
                       return AutoFeatureExtractor.from_pretrained(
                           A_					,					trust_remote_code=A_					,					**A_    )
                 except Exception:
                       pass

           raise ValueError(
               F'Unrecognized processing class in {pretrained_model_name_or_path}. Can\'t instantiate a processor, a '
               '''tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains'''
               '''the files of at least one of those processing classes.'''    )





     @staticmethod
     def 		UpperCamelCase_    (       A_					,					A_    )			->					List[Any]:






           """simple docstring"""
           PROCESSOR_MAPPING.register(A_					,					A_    )