




"""simple docstring"""



from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


SCREAMING_SNAKE_CASE    =	logging.get_logger(__name__)




class      UpperCAmelCase_  (						A_							):




    def __init__(   self						:	Tuple     ,			snake_case_						:	int     ,			snake_case_						:	int     ,			snake_case_						:	float     ,			**snake_case_						:	Dict				)				->							Union[str, Any]:




     '''simple docstring'''

     A__	=    feature_size
     A__	=    sampling_rate
     A__	=    padding_value

     A__	=    kwargs.pop("padding_side"     ,			"right"				)
     A__	=    kwargs.pop("return_attention_mask"     ,			snake_case_				)

     super().__init__(**snake_case_				)




    def 							__magic_name__							(   self						:	Dict     ,			snake_case_						:	Union[
            BatchFeature,
            List[BatchFeature],
            Dict[str, BatchFeature],
            Dict[str, List[BatchFeature]],
            List[Dict[str, BatchFeature]],
        ]     ,			snake_case_						:	Union[bool, str, PaddingStrategy] = True     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	bool = False     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	Optional[bool] = None     ,			snake_case_						:	Optional[Union[str, TensorType]] = None     ,			)				->							BatchFeature:




     '''simple docstring'''

     if isinstance(snake_case_     ,			(list, tuple)				) and isinstance(processed_features[0]     ,			(dict, BatchFeature)				):
      A__	=    {
          key: [example[key] for example in processed_features] for key in processed_features[0].keys()
      }

     # The model's main input name, usually `input_values`, has be passed for padding
     if self.model_input_names[0] not in processed_features:
      raise ValueError(
          "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
          F""" to this method that includes {self.model_input_names[0]}, but you provided"""
          F""" {list(processed_features.keys()				)}"""				)

     A__	=    processed_features[self.model_input_names[0]]
     A__	=    (
         return_attention_mask if return_attention_mask is not None else self.return_attention_mask
     )

     if len(snake_case_				) == 0:
      if return_attention_mask:
       A__	=    []
      return processed_features

     # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
     # and rebuild them afterwards if no return_tensors is specified
     # Note that we lose the specific device the tensor may be on for PyTorch

     A__	=    required_input[0]
     if isinstance(snake_case_     ,			(list, tuple)				):
      # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
      A__	=    0
      while len(required_input[index]				) == 0:
       index += 1
      if index < len(snake_case_				):
       A__	=    required_input[index][0]

     if return_tensors is None:
      if is_tf_tensor(snake_case_				):
       A__	=    "tf"
      elif is_torch_tensor(snake_case_				):
       A__	=    "pt"
      elif isinstance(snake_case_     ,			(int, float, list, tuple, np.ndarray)				):
       A__	=    "np"
      else:
       raise ValueError(
           F"""type of {first_element} unknown: {type(snake_case_				)}. """
           "Should be one of a python, numpy, pytorch or tensorflow object."				)

     for key, value in processed_features.items():
      if isinstance(value[0]     ,			(int, float)				):
       A__	=    to_numpy(snake_case_				)
      else:
       A__	=    [to_numpy(snake_case_				) for v in value]

        # Convert padding_strategy in PaddingStrategy
     A__	=    self._get_padding_strategies(padding=snake_case_     ,			max_length=snake_case_				)

     A__	=    processed_features[self.model_input_names[0]]

     A__	=    len(snake_case_				)
     if not all(len(snake_case_				) == batch_size for v in processed_features.values()				):
      raise ValueError("Some items in the output dictionary have a different batch size than others."				)

     A__	=    []
     for i in range(snake_case_				):
      A__	=    {k: v[i] for k, v in processed_features.items()}
      # truncation
      A__	=    self._truncate(
          snake_case_     ,			max_length=snake_case_     ,			pad_to_multiple_of=snake_case_     ,			truncation=snake_case_     ,			)
      truncated_inputs.append(snake_case_				)

     if padding_strategy == PaddingStrategy.LONGEST:
      # make sure that `max_length` cannot be longer than the longest truncated length
      A__	=    max(len(input_slice[self.model_input_names[0]]				) for input_slice in truncated_inputs				)
      A__	=    PaddingStrategy.MAX_LENGTH

     A__	=    {}
     for i in range(snake_case_				):
      # padding
      A__	=    self._pad(
          truncated_inputs[i]     ,			max_length=snake_case_     ,			padding_strategy=snake_case_     ,			pad_to_multiple_of=snake_case_     ,			return_attention_mask=snake_case_     ,			)

      for key, value in outputs.items():
       if key not in batch_outputs:
        A__	=    []
       if value.dtype is np.dtype(np.floataa				):
        A__	=    value.astype(np.floataa				)
       batch_outputs[key].append(snake_case_				)

     return BatchFeature(snake_case_     ,			tensor_type=snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]     ,			snake_case_						:	Union[Dict[str, np.ndarray], BatchFeature]     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	PaddingStrategy = PaddingStrategy.DO_NOT_PAD     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	Optional[bool] = None     ,			)				->							dict:




     '''simple docstring'''

     A__	=    processed_features[self.model_input_names[0]]

     if padding_strategy == PaddingStrategy.LONGEST:
      A__	=    len(snake_case_				)

     if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
      A__	=    ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

     A__	=    padding_strategy != PaddingStrategy.DO_NOT_PAD and len(snake_case_				) < max_length

     if return_attention_mask and "attention_mask" not in processed_features:
      A__	=    np.ones(len(snake_case_				)     ,			dtype=np.intaa				)

     if needs_to_be_padded:
      A__	=    max_length - len(snake_case_				)
      if self.padding_side == "right":
       if return_attention_mask:
        A__	=    np.pad(
            processed_features["attention_mask"]     ,			(0, difference)				)
       A__	=    ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
       A__	=    np.pad(
           snake_case_     ,			snake_case_     ,			"constant"     ,			constant_values=self.padding_value				)
      elif self.padding_side == "left":
       if return_attention_mask:
        A__	=    np.pad(
            processed_features["attention_mask"]     ,			(difference, 0)				)
       A__	=    ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
       A__	=    np.pad(
           snake_case_     ,			snake_case_     ,			"constant"     ,			constant_values=self.padding_value				)
      else:
       raise ValueError("Invalid padding strategy:" + str(self.padding_side				)				)

     return processed_features




    def 							__magic_name__							(   self						:	Optional[int]     ,			snake_case_						:	Union[Dict[str, np.ndarray], BatchFeature]     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	Optional[int] = None     ,			snake_case_						:	Optional[bool] = None     ,			)				->							Any:




     '''simple docstring'''

     if not truncation:
      return processed_features
     elif truncation and max_length is None:
      raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined."				)

     A__	=    processed_features[self.model_input_names[0]]

     # find `max_length` that fits `pad_to_multiple_of`
     if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
      A__	=    ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

     A__	=    len(snake_case_				) > max_length

     if needs_to_be_truncated:
      A__	=    processed_features[self.model_input_names[0]][:max_length]
      if "attention_mask" in processed_features:
       A__	=    processed_features["attention_mask"][:max_length]

     return processed_features




    def 							__magic_name__							(   self						:	str     ,			snake_case_						:	Optional[int]=False     ,			snake_case_						:	Dict=None				)				->							List[str]:




     '''simple docstring'''

     if padding is not False:
      if padding is True:
       A__	=    PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
      elif not isinstance(snake_case_     ,			snake_case_				):
       A__	=    PaddingStrategy(snake_case_				)
      elif isinstance(snake_case_     ,			snake_case_				):
       A__	=    padding
     else:
      A__	=    PaddingStrategy.DO_NOT_PAD

     # Set max length if needed
     if max_length is None:
      if padding_strategy == PaddingStrategy.MAX_LENGTH:
       raise ValueError(
           F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"""				)

        # Test if we have a padding value
     if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
      raise ValueError(
          "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
          " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."				)

     return padding_strategy











"""simple docstring"""



import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class      UpperCAmelCase_  (						A_							):
    lowercase__						 =				['''image_processor''', '''tokenizer''']
    lowercase__						 =				'''ViTImageProcessor'''
    lowercase__						 =				('''CLIPTokenizer''', '''CLIPTokenizerFast''')




    def __init__(   self						:	Optional[Any]     ,			snake_case_						:	Union[str, Any]=None     ,			snake_case_						:	Dict=None     ,			**snake_case_						:	Optional[Any]				)				->							List[str]:




     '''simple docstring'''

     A__	=    None
     if "feature_extractor" in kwargs:
      warnings.warn(
          "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
          " instead."     ,			snake_case_     ,			)
      A__	=    kwargs.pop("feature_extractor"				)

     A__	=    image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
      raise ValueError("You need to specify an `image_processor`."				)
     if tokenizer is None:
      raise ValueError("You need to specify a `tokenizer`."				)

     super().__init__(snake_case_     ,			snake_case_				)




    def __call__(   self						:	int     ,			snake_case_						:	Union[str, Any]=None     ,			snake_case_						:	int=None     ,			snake_case_						:	Dict=None     ,			snake_case_						:	int=None     ,			**snake_case_						:	List[str]				)				->							Union[str, Any]:




     '''simple docstring'''

     if text is None and visual_prompt is None and images is None:
      raise ValueError("You have to specify either text, visual prompt or images."				)

     if text is not None and visual_prompt is not None:
      raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt."				)

     if text is not None:
      A__	=    self.tokenizer(snake_case_     ,			return_tensors=snake_case_     ,			**snake_case_				)

     if visual_prompt is not None:
      A__	=    self.image_processor(snake_case_     ,			return_tensors=snake_case_     ,			**snake_case_				)

     if images is not None:
      A__	=    self.image_processor(snake_case_     ,			return_tensors=snake_case_     ,			**snake_case_				)

     if visual_prompt is not None and images is not None:
      A__	=    {
          "pixel_values": image_features.pixel_values,
          "conditional_pixel_values": prompt_features.pixel_values,
      }
      return encoding
     elif text is not None and images is not None:
      A__	=    image_features.pixel_values
      return encoding
     elif text is not None:
      return encoding
     elif visual_prompt is not None:
      A__	=    {
          "conditional_pixel_values": prompt_features.pixel_values,
      }
      return encoding
     else:
      return BatchEncoding(data=dict(**snake_case_				)     ,			tensor_type=snake_case_				)




    def 							__magic_name__							(   self						:	Tuple     ,			*snake_case_						:	List[str]     ,			**snake_case_						:	Optional[int]				)				->							str:




     '''simple docstring'''

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




    def 							__magic_name__							(   self						:	Optional[Any]     ,			*snake_case_						:	Any     ,			**snake_case_						:	List[Any]				)				->							List[str]:




     '''simple docstring'''

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




    @property
    def 							__magic_name__							(   self						:	int				)				->							Optional[int]:




     '''simple docstring'''

     warnings.warn(
         "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."     ,			snake_case_     ,			)
     return self.image_processor_class




    @property
    def 							__magic_name__							(   self						:	int				)				->							int:




     '''simple docstring'''

     warnings.warn(
         "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."     ,			snake_case_     ,			)
     return self.image_processor





