


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       _lowercase			(							_a):


       """simple docstring"""




       A__ 						=      CONFIG_NAME





       @register_to_config
       def __init__(       self							:      str ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      int = 8 ,				__lowerCamelCase							:      str = "lanczos" ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      bool = False ,				):


             '''simple docstring'''



             super().__init__()





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      np.ndarray	):


             '''simple docstring'''



             if images.ndim == 3:
                   lowerCamelCase__		:    Optional[int]   =  images[None, ...]
             lowerCamelCase__		:    Optional[Any]   =  (images * 255).round().astype("uint8"	)
             if images.shape[-1] == 1:
                   # special case for grayscale (single channel) images
                   lowerCamelCase__		:    Dict   =  [Image.fromarray(image.squeeze() ,				mode="L"	) for image in images]
             else:
                   lowerCamelCase__		:    Any   =  [Image.fromarray(SCREAMING_SNAKE_CASE__	) for image in images]

             return pil_images





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      Union[List[PIL.Image.Image], PIL.Image.Image]	):


             '''simple docstring'''



             if not isinstance(SCREAMING_SNAKE_CASE__ ,				SCREAMING_SNAKE_CASE__	):
                   lowerCamelCase__		:    Any   =  [images]
             lowerCamelCase__		:    str   =  [np.array(SCREAMING_SNAKE_CASE__	).astype(np.floataa	) / 2_5_5.0 for image in images]
             lowerCamelCase__		:    List[Any]   =  np.stack(SCREAMING_SNAKE_CASE__ ,				axis=0	)

             return images





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      np.ndarray	):


             '''simple docstring'''



             if images.ndim == 3:
                   lowerCamelCase__		:    Optional[int]   =  images[..., None]

             lowerCamelCase__		:    Any   =  torch.from_numpy(images.transpose(0 ,				3 ,				1 ,				2	)	)
             return images





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      torch.FloatTensor	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  images.cpu().permute(0 ,				2 ,				3 ,				1	).float().numpy()
             return images





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      List[str]	):


             '''simple docstring'''



             return 2.0 * images - 1.0





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      Dict	):


             '''simple docstring'''



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





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      PIL.Image.Image	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  image.convert("RGB"	)
             return image





       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      PIL.Image.Image ,				__lowerCamelCase							:      Optional[int] = None ,				__lowerCamelCase							:      Optional[int] = None ,				):


             '''simple docstring'''



             if height is None:
                   lowerCamelCase__		:    Any   =  image.height
             if width is None:
                   lowerCamelCase__		:    Optional[Any]   =  image.width

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





       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      Union[torch.FloatTensor, PIL.Image.Image, np.ndarray] ,				__lowerCamelCase							:      Optional[int] = None ,				__lowerCamelCase							:      Optional[int] = None ,				):


             '''simple docstring'''



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

             if isinstance(image[0] ,				PIL.Image.Image	):
                   if self.config.do_convert_rgb:
                         lowerCamelCase__		:    str   =  [self.convert_to_rgb(SCREAMING_SNAKE_CASE__	) for i in image]
                   if self.config.do_resize:
                         lowerCamelCase__		:    Union[str, Any]   =  [self.resize(SCREAMING_SNAKE_CASE__ ,				SCREAMING_SNAKE_CASE__ ,				SCREAMING_SNAKE_CASE__	) for i in image]
                   lowerCamelCase__		:    List[Any]   =  self.pil_to_numpy(SCREAMING_SNAKE_CASE__	)  # to np
                   lowerCamelCase__		:    Optional[Any]   =  self.numpy_to_pt(SCREAMING_SNAKE_CASE__	)  # to pt

             elif isinstance(image[0] ,				np.ndarray	):
                   lowerCamelCase__		:    Any   =  np.concatenate(SCREAMING_SNAKE_CASE__ ,				axis=0	) if image[0].ndim == 4 else np.stack(SCREAMING_SNAKE_CASE__ ,				axis=0	)
                   lowerCamelCase__		:    Optional[Any]   =  self.numpy_to_pt(SCREAMING_SNAKE_CASE__	)
                   lowerCamelCase__		:    Optional[Any]   =  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__		:    Optional[Any]   =  torch.cat(SCREAMING_SNAKE_CASE__ ,				axis=0	) if image[0].ndim == 4 else torch.stack(SCREAMING_SNAKE_CASE__ ,				axis=0	)
                   lowerCamelCase__		:    str   =  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__		:    int   =  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()}]" ,				SCREAMING_SNAKE_CASE__ ,				)
                   lowerCamelCase__		:    Union[str, Any]   =  False

             if do_normalize:
                   lowerCamelCase__		:    List[str]   =  self.normalize(SCREAMING_SNAKE_CASE__	)

             return image





       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      torch.FloatTensor ,				__lowerCamelCase							:      str = "pil" ,				__lowerCamelCase							:      Optional[List[bool]] = None ,				):


             '''simple docstring'''



             if not isinstance(SCREAMING_SNAKE_CASE__ ,				torch.Tensor	):
                   raise ValueError(
                       f"Input for postprocessing is in incorrect format: {type(SCREAMING_SNAKE_CASE__	)}. We only support pytorch tensor"	)
             if output_type not in ["latent", "pt", "np", "pil"]:
                   lowerCamelCase__		:    List[Any]   =  (
                       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" ,				SCREAMING_SNAKE_CASE__ ,				standard_warn=SCREAMING_SNAKE_CASE__	)
                   lowerCamelCase__		:    List[str]   =  "np"

             if output_type == "latent":
                   return image

             if do_denormalize is None:
                   lowerCamelCase__		:    Union[str, Any]   =  [self.config.do_normalize] * image.shape[0]

             lowerCamelCase__		:    Union[str, Any]   =  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__		:    Tuple   =  self.pt_to_numpy(SCREAMING_SNAKE_CASE__	)

             if output_type == "np":
                   return image

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







class       _lowercase			(							_a):


       """simple docstring"""




       A__ 						=      CONFIG_NAME





       @register_to_config
       def __init__(       self							:      Optional[Any] ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      int = 8 ,				__lowerCamelCase							:      str = "lanczos" ,				__lowerCamelCase							:      bool = True ,				):


             '''simple docstring'''



             super().__init__()





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      Optional[int]	):


             '''simple docstring'''



             if images.ndim == 3:
                   lowerCamelCase__		:    Tuple   =  images[None, ...]
             lowerCamelCase__		:    Union[str, Any]   =  (images * 255).round().astype("uint8"	)
             if images.shape[-1] == 1:
                   # special case for grayscale (single channel) images
                   lowerCamelCase__		:    str   =  [Image.fromarray(image.squeeze() ,				mode="L"	) for image in images]
             else:
                   lowerCamelCase__		:    Tuple   =  [Image.fromarray(image[:, :, :3]	) for image in images]

             return pil_images





       @staticmethod
       def 						lowerCAmelCase					(       __lowerCamelCase							:      int	):


             '''simple docstring'''



             return image[:, :, 1] * 2**8 + image[:, :, 2]





       def 						lowerCAmelCase					(       self							:      int ,				__lowerCamelCase							:      Optional[Any]	):


             '''simple docstring'''



             if images.ndim == 3:
                   lowerCamelCase__		:    Union[str, Any]   =  images[None, ...]
             lowerCamelCase__		:    Optional[Any]   =  images[:, :, :, 3:]
             if images.shape[-1] == 6:
                   lowerCamelCase__		:    Optional[int]   =  (images_depth * 255).round().astype("uint8"	)
                   lowerCamelCase__		:    Tuple   =  [
                       Image.fromarray(self.rgblike_to_depthmap(SCREAMING_SNAKE_CASE__	) ,				mode="I;16"	) for image_depth in images_depth
                   ]
             elif images.shape[-1] == 4:
                   lowerCamelCase__		:    List[str]   =  (images_depth * 65535.0).astype(np.uintaa	)
                   lowerCamelCase__		:    Dict   =  [Image.fromarray(SCREAMING_SNAKE_CASE__ ,				mode="I;16"	) for image_depth in images_depth]
             else:
                   raise Exception("Not supported"	)

             return pil_images





       def 						lowerCAmelCase					(       self							:      Any ,				__lowerCamelCase							:      torch.FloatTensor ,				__lowerCamelCase							:      str = "pil" ,				__lowerCamelCase							:      Optional[List[bool]] = None ,				):


             '''simple docstring'''



             if not isinstance(SCREAMING_SNAKE_CASE__ ,				torch.Tensor	):
                   raise ValueError(
                       f"Input for postprocessing is in incorrect format: {type(SCREAMING_SNAKE_CASE__	)}. We only support pytorch tensor"	)
             if output_type not in ["latent", "pt", "np", "pil"]:
                   lowerCamelCase__		:    Union[str, Any]   =  (
                       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" ,				SCREAMING_SNAKE_CASE__ ,				standard_warn=SCREAMING_SNAKE_CASE__	)
                   lowerCamelCase__		:    List[str]   =  "np"

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

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

             lowerCamelCase__		:    Union[str, Any]   =  self.pt_to_numpy(SCREAMING_SNAKE_CASE__	)

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

             if output_type == "pil":
                   return self.numpy_to_pil(SCREAMING_SNAKE_CASE__	), self.numpy_to_depth(SCREAMING_SNAKE_CASE__	)
             else:
                   raise Exception(f"This type {output_type} is not supported"	)






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin







class       _lowercase			(							lowercase__):


       """simple docstring"""




       A__ 						=      "AutoFeatureExtractor"
       A__ 						=      "Speech2Text2Tokenizer"





       def __init__(       self							:      List[str] ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      str	):


             '''simple docstring'''



             super().__init__(__lowerCamelCase ,				__lowerCamelCase	)
             lowerCamelCase__		:    Optional[Any]   =  self.feature_extractor
             lowerCamelCase__		:    Optional[int]   =  False





       def __call__(       self							:      List[str] ,				*__lowerCamelCase							:      Union[str, Any] ,				**__lowerCamelCase							:      List[Any]	):


             '''simple docstring'''



             if self._in_target_context_manager:
                   return self.current_processor(*__lowerCamelCase ,				**__lowerCamelCase	)

             if "raw_speech" in kwargs:
                   warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."	)
                   lowerCamelCase__		:    List[Any]   =  kwargs.pop("raw_speech"	)
             else:
                   lowerCamelCase__		:    str   =  kwargs.pop("audio" ,				__lowerCamelCase	)
             lowerCamelCase__		:    Optional[Any]   =  kwargs.pop("sampling_rate" ,				__lowerCamelCase	)
             lowerCamelCase__		:    Union[str, Any]   =  kwargs.pop("text" ,				__lowerCamelCase	)
             if len(__lowerCamelCase	) > 0:
                   lowerCamelCase__		:    Dict   =  args[0]
                   lowerCamelCase__		:    int   =  args[1:]

             if audio is None and text is None:
                   raise ValueError("You need to specify either an `audio` or `text` input to process."	)

             if audio is not None:
                   lowerCamelCase__		:    str   =  self.feature_extractor(__lowerCamelCase ,				*__lowerCamelCase ,				sampling_rate=__lowerCamelCase ,				**__lowerCamelCase	)
             if text is not None:
                   lowerCamelCase__		:    Optional[int]   =  self.tokenizer(__lowerCamelCase ,				**__lowerCamelCase	)

             if text is None:
                   return inputs
             elif audio is None:
                   return encodings
             else:
                   lowerCamelCase__		:    Optional[int]   =  encodings["input_ids"]
                   return inputs





       def 						lowerCAmelCase					(       self							:      Any ,				*__lowerCamelCase							:      Any ,				**__lowerCamelCase							:      Any	):


             '''simple docstring'''



             return self.tokenizer.batch_decode(*__lowerCamelCase ,				**__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Dict ,				*__lowerCamelCase							:      int ,				**__lowerCamelCase							:      List[str]	):


             '''simple docstring'''



             return self.tokenizer.decode(*__lowerCamelCase ,				**__lowerCamelCase	)





       @contextmanager
       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             warnings.warn(
                 "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
                 "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
                 "your audio inputs, or in a separate call."	)
             lowerCamelCase__		:    int   =  True
             lowerCamelCase__		:    List[Any]   =  self.tokenizer
             yield
             lowerCamelCase__		:    Optional[int]   =  self.feature_extractor
             lowerCamelCase__		:    List[str]   =  False


