

'''simple docstring'''
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


lowerCamelCase :      Dict					 =     logging.get_logger(__name__)


lowerCamelCase :      Any					 =     r"\n    Args:\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n            or scores for each vocabulary token after SoftMax.\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional stopping criteria specific kwargs.\n\n    Return:\n        `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n"







class 							A__    (       A__  ):





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





       '''simple docstring'''






       raise NotImplementedError('StoppingCriteria needs to be subclassed' )







class 							A__    (       A__  ):





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





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =max_length
       _SCREAMING_SNAKE_CASE							    =max_position_embeddings





  @add_start_docstrings(_a )
  def __call__(		self      :	List[str]							,					_a      :	torch.LongTensor							,					_a      :	torch.FloatTensor							,					**_a      :	Tuple )	->    bool:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =input_ids.shape[-1]
       _SCREAMING_SNAKE_CASE							    =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 							A__    (       A__  ):





  def __init__(		self      :	Optional[int]							,					_a      :	int							,					_a      :	int )	->    Optional[int]:





       '''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.'							,					_a							,					)
       _SCREAMING_SNAKE_CASE							    =start_length
       _SCREAMING_SNAKE_CASE							    =max_new_tokens
       _SCREAMING_SNAKE_CASE							    =start_length + max_new_tokens





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





       '''simple docstring'''






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







class 							A__    (       A__  ):





  def __init__(		self      :	Optional[int]							,					_a      :	float							,					_a      :	Optional[float] = None )	->    Optional[Any]:





       '''simple docstring'''






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





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





       '''simple docstring'''






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







class 							A__    (       A__  ):





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





       '''simple docstring'''






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





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





       '''simple docstring'''






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


def        _lowerCAmelCase					(						_UpperCamelCase						:     StoppingCriteriaList							, _UpperCamelCase						:     int				)      ->			StoppingCriteriaList:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =stopping_criteria.max_length
     _SCREAMING_SNAKE_CASE							    =deepcopy(_UpperCamelCase				)
     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'							, _UpperCamelCase				)
     elif stopping_max_length is None:
          new_stopping_criteria.append(MaxLengthCriteria(max_length=_UpperCamelCase				)				)
     return new_stopping_criteria



'''simple docstring'''
import numpy as np
from PIL import Image


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =np.array(_UpperCamelCase				)
     if arr.shape[0] != arr.shape[1]:
          raise ValueError('The input array is not a square matrix'				)
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0

     # compute the shape of the output matrix
     _SCREAMING_SNAKE_CASE							    =(arr.shape[0] - size) // stride + 1
     # initialize the output matrix with zeros of shape maxpool_shape
     _SCREAMING_SNAKE_CASE							    =np.zeros((maxpool_shape, maxpool_shape)				)

     while i < arr.shape[0]:
          if i + size > arr.shape[0]:
               # if the end of the matrix is reached, break
               break
          while j < arr.shape[1]:
               # if the end of the matrix is reached, break
               if j + size > arr.shape[1]:
                    break
               # compute the maximum of the pooling matrix
               _SCREAMING_SNAKE_CASE							    =np.max(arr[i : i + size, j : j + size]				)
               # shift the pooling matrix by stride of column pixels
               j += stride
               mat_j += 1

          # shift the pooling matrix by stride of row pixels
          i += stride
          mat_i += 1

          # reset the column index to 0
          _SCREAMING_SNAKE_CASE							    =0
          _SCREAMING_SNAKE_CASE							    =0

     return updated_arr


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =np.array(_UpperCamelCase				)
     if arr.shape[0] != arr.shape[1]:
          raise ValueError('The input array is not a square matrix'				)
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0

     # compute the shape of the output matrix
     _SCREAMING_SNAKE_CASE							    =(arr.shape[0] - size) // stride + 1
     # initialize the output matrix with zeros of shape avgpool_shape
     _SCREAMING_SNAKE_CASE							    =np.zeros((avgpool_shape, avgpool_shape)				)

     while i < arr.shape[0]:
          # if the end of the matrix is reached, break
          if i + size > arr.shape[0]:
               break
          while j < arr.shape[1]:
               # if the end of the matrix is reached, break
               if j + size > arr.shape[1]:
                    break
               # compute the average of the pooling matrix
               _SCREAMING_SNAKE_CASE							    =int(np.average(arr[i : i + size, j : j + size]				)				)
               # shift the pooling matrix by stride of column pixels
               j += stride
               mat_j += 1

          # shift the pooling matrix by stride of row pixels
          i += stride
          mat_i += 1
          # reset the column index to 0
          _SCREAMING_SNAKE_CASE							    =0
          _SCREAMING_SNAKE_CASE							    =0

     return updated_arr


# Main Function
if __name__ == "__main__":
     from doctest import testmod

     testmod(name="avgpooling", verbose=True)

     # Loading the image
     lowerCamelCase :      Optional[Any]					 =     Image.open("path_to_image")

     # Converting the image to numpy array and maxpooling, displaying the result
     # Ensure that the image is a square matrix

     Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

     # Converting the image to numpy array and averagepooling, displaying the result
     # Ensure that the image is a square matrix

     Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
