import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


a_							=      logging.get_logger(__name__)


a_							=      r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""


class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  @add_start_docstrings(__lowerCAmelCase   )
  def __call__(				self:			Optional[Any]				,				__lowerCAmelCase:			torch.LongTensor				,				__lowerCAmelCase:			torch.FloatTensor				,				**__lowerCAmelCase:			Dict   ) -> bool:




    '''simple docstring'''




    raise NotImplementedError("StoppingCriteria needs to be subclassed"   )






class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  def __init__(				self:			str				,				__lowerCAmelCase:			int				,				__lowerCAmelCase:			Optional[int] = None   ) -> List[str]:




    '''simple docstring'''




    __UpperCAmelCase						    =       max_length
    __UpperCAmelCase						    =       max_position_embeddings






  @add_start_docstrings(__lowerCAmelCase   )
  def __call__(				self:			Optional[Any]				,				__lowerCAmelCase:			torch.LongTensor				,				__lowerCAmelCase:			torch.FloatTensor				,				**__lowerCAmelCase:			List[Any]   ) -> bool:




    '''simple docstring'''




    __UpperCAmelCase						    =       input_ids.shape[-1]
    __UpperCAmelCase						    =       cur_len >= self.max_length
    if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
      logger.warning_once(
          "This is a friendly reminder - the current text generation call will exceed the model's predefined "
          F'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe '''
          "exceptions, performance degradation, or nothing at all."   )
    return is_done






class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  def __init__(				self:			Tuple				,				__lowerCAmelCase:			int				,				__lowerCAmelCase:			int   ) -> Optional[Any]:




    '''simple docstring'''




    warnings.warn(
        "The class `MaxNewTokensCriteria` is deprecated. "
        F'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` '''
        "with `max_length = start_length + max_new_tokens` instead."				,				__lowerCAmelCase				,				)
    __UpperCAmelCase						    =       start_length
    __UpperCAmelCase						    =       max_new_tokens
    __UpperCAmelCase						    =       start_length + max_new_tokens






  @add_start_docstrings(__lowerCAmelCase   )
  def __call__(				self:			Optional[Any]				,				__lowerCAmelCase:			torch.LongTensor				,				__lowerCAmelCase:			torch.FloatTensor				,				**__lowerCAmelCase:			Optional[Any]   ) -> bool:




    '''simple docstring'''




    return input_ids.shape[-1] >= self.max_length






class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  def __init__(				self:			List[Any]				,				__lowerCAmelCase:			float				,				__lowerCAmelCase:			Optional[float] = None   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       max_time
    __UpperCAmelCase						    =       time.time() if initial_timestamp is None else initial_timestamp






  @add_start_docstrings(__lowerCAmelCase   )
  def __call__(				self:			List[Any]				,				__lowerCAmelCase:			torch.LongTensor				,				__lowerCAmelCase:			torch.FloatTensor				,				**__lowerCAmelCase:			Dict   ) -> bool:




    '''simple docstring'''




    return time.time() - self.initial_timestamp > self.max_time






class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  @add_start_docstrings(__lowerCAmelCase   )
  def __call__(				self:			Tuple				,				__lowerCAmelCase:			torch.LongTensor				,				__lowerCAmelCase:			torch.FloatTensor				,				**__lowerCAmelCase:			Tuple   ) -> bool:




    '''simple docstring'''




    return any(criteria(__lowerCAmelCase				,				__lowerCAmelCase   ) for criteria in self   )






  @property
  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> Optional[int]:




    '''simple docstring'''




    for stopping_criterium in self:
      if isinstance(__lowerCAmelCase				,				__lowerCAmelCase   ):
        return stopping_criterium.max_length
      elif isinstance(__lowerCAmelCase				,				__lowerCAmelCase   ):
        return stopping_criterium.max_length
    return None






def       __lowerCAmelCase      (						A_   : StoppingCriteriaList						,	A_   : int					)    ->  StoppingCriteriaList:
  __UpperCAmelCase						    =       stopping_criteria.max_length
  __UpperCAmelCase						    =       deepcopy(A_					)
  if stopping_max_length is not None and stopping_max_length != max_length:
    warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"						,	A_					)
  elif stopping_max_length is None:
    new_stopping_criteria.append(MaxLengthCriteria(max_length=A_					)					)
  return new_stopping_criteria




import warnings

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


class 			UpperCAmelCase__    (		snake_case					):



  """simple docstring"""






  lowerCAmelCase__		:	Optional[int]    		= ['image_processor', 'tokenizer']
  lowerCAmelCase__		:	Any    		= 'CLIPImageProcessor'
  lowerCAmelCase__		:	Any    		= ('CLIPTokenizer', 'CLIPTokenizerFast')






  def __init__(				self:			str				,				__lowerCAmelCase:			List[Any]=None				,				__lowerCAmelCase:			Any=None				,				**__lowerCAmelCase:			str   ) -> Optional[int]:




    '''simple docstring'''




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

    __UpperCAmelCase						    =       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__(__lowerCAmelCase				,				__lowerCAmelCase   )






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




    '''simple docstring'''




    if text is None and images is None:
      raise ValueError("You have to specify either text or images. Both cannot be none."   )

    if text is not None:
      __UpperCAmelCase						    =       self.tokenizer(__lowerCAmelCase				,				return_tensors=__lowerCAmelCase				,				**__lowerCAmelCase   )

    if images is not None:
      __UpperCAmelCase						    =       self.image_processor(__lowerCAmelCase				,				return_tensors=__lowerCAmelCase				,				**__lowerCAmelCase   )

    if text is not None and images is not None:
      __UpperCAmelCase						    =       image_features.pixel_values
      return encoding
    elif text is not None:
      return encoding
    else:
      return BatchEncoding(data=dict(**__lowerCAmelCase   )				,				tensor_type=__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			str				,				*__lowerCAmelCase:			str				,				**__lowerCAmelCase:			List[Any]   ) -> Optional[Any]:




    '''simple docstring'''




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






  def 	_UpperCAmelCase				(				self:			Any				,				*__lowerCAmelCase:			List[Any]				,				**__lowerCAmelCase:			Dict   ) -> Union[str, Any]:




    '''simple docstring'''




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






  @property
  def 	_UpperCAmelCase				(				self:			Tuple   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       self.tokenizer.model_input_names
    __UpperCAmelCase						    =       self.image_processor.model_input_names
    return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names   )   )






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




    '''simple docstring'''




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






  @property
  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> List[str]:




    '''simple docstring'''




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



