
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


lowercase  :					Optional[int]						    =							logging.get_logger(__name__)


lowercase  :					Dict						    =							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 __snake_case		(      lowerCAmelCase     ):
    @add_start_docstrings(snake_case      )
    def __call__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







           raise NotImplementedError("""StoppingCriteria needs to be subclassed"""      )






class __snake_case		(      lowerCAmelCase     ):
    def __init__(  self		,snake_case		,snake_case = None      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      max_length
           lowercase							:     Union[str, Any]       	=      max_position_embeddings
    @add_start_docstrings(snake_case      )
    def __call__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      input_ids.shape[-1]
           lowercase							:     Dict       	=      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 __snake_case		(      lowerCAmelCase     ):
    def __init__(  self		,snake_case		,snake_case      ):



           '''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."""		,snake_case		,)
           lowercase							:     Dict       	=      start_length
           lowercase							:     Any       	=      max_new_tokens
           lowercase							:     List[Any]       	=      start_length + max_new_tokens
    @add_start_docstrings(snake_case      )
    def __call__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







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






class __snake_case		(      lowerCAmelCase     ):
    def __init__(  self		,snake_case		,snake_case = None      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      max_time
           lowercase							:     Optional[Any]       	=      time.time() if initial_timestamp is None else initial_timestamp
    @add_start_docstrings(snake_case      )
    def __call__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







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






class __snake_case		(      lowerCAmelCase     ):
    @add_start_docstrings(snake_case      )
    def __call__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







           return any(criteria(snake_case		,snake_case      ) for criteria in self      )
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    StoppingCriteriaList:
       lowercase							:     str       	=      stopping_criteria.max_length
       lowercase							:     int       	=      deepcopy(SCREAMING_SNAKE_CASE__				)
       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"""					,	SCREAMING_SNAKE_CASE__				)
       elif stopping_max_length is None:
              new_stopping_criteria.append(MaxLengthCriteria(max_length=SCREAMING_SNAKE_CASE__				)				)
       return new_stopping_criteria


import unittest

from huggingface_hub import hf_hub_download

from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_decord,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
)

from .test_pipelines_common import ANY

@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class __snake_case		(      unittest.TestCase     ):
    _a		:						Optional[int]=				MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Any       	=      hf_hub_download(
               repo_id="""nateraw/video-demo"""		,filename="""archery.mp4"""		,repo_type="""dataset"""      )
           lowercase							:     List[str]       	=      VideoClassificationPipeline(model=snake_case		,image_processor=snake_case		,top_k=2      )
           lowercase							:     Dict       	=      [
               example_video_filepath,
               """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""",
           ]
           return video_classifier, examples
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case      ):



           '''simple docstring'''







           for example in examples:
                  lowercase							:     int       	=      video_classifier(snake_case      )

                  self.assertEqual(
                      snake_case		,[
                          {"""score""": ANY(snake_case      ), """label""": ANY(snake_case      )},
                          {"""score""": ANY(snake_case      ), """label""": ANY(snake_case      )},
                      ]		,)
    @require_torch
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Any       	=      """hf-internal-testing/tiny-random-VideoMAEForVideoClassification"""
           lowercase							:     str       	=      VideoMAEFeatureExtractor(
               size={"""shortest_edge""": 10}		,crop_size={"""height""": 10, """width""": 10}      )
           lowercase							:     List[Any]       	=      pipeline(
               """video-classification"""		,model=snake_case		,feature_extractor=snake_case		,frame_sampling_rate=4      )

           lowercase							:     Dict       	=      hf_hub_download(repo_id="""nateraw/video-demo"""		,filename="""archery.mp4"""		,repo_type="""dataset"""      )
           lowercase							:     Any       	=      video_classifier(snake_case		,top_k=2      )
           self.assertEqual(
               nested_simplify(snake_case		,decimals=4      )		,[{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}]		,)

           lowercase							:     str       	=      video_classifier(
               [
                   video_file_path,
                   video_file_path,
               ]		,top_k=2		,)
           self.assertEqual(
               nested_simplify(snake_case		,decimals=4      )		,[
                   [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}],
                   [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}],
               ]		,)
    @require_tf
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           pass
