



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						  =		logging.get_logger(__name__)


_lowercase						  =		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     _UpperCAmelCase			(       A__     ):




     @add_start_docstrings(a__)
     def __call__(				self ,						a__ ,						a__ ,						**a__):
         raise NotImplementedError('''StoppingCriteria needs to be subclassed''')







class     _UpperCAmelCase			(       A__     ):




     def __init__(				self ,						a__ ,						a__ = None):
         A__		 =					max_length
         A__		 =					max_position_embeddings




     @add_start_docstrings(a__)
     def __call__(				self ,						a__ ,						a__ ,						**a__):
         A__		 =					input_ids.shape[-1]
         A__		 =					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			(       A__     ):




     def __init__(				self ,						a__ ,						a__):
         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__ ,						)
         A__		 =					start_length
         A__		 =					max_new_tokens
         A__		 =					start_length + max_new_tokens




     @add_start_docstrings(a__)
     def __call__(				self ,						a__ ,						a__ ,						**a__):
         return input_ids.shape[-1] >= self.max_length







class     _UpperCAmelCase			(       A__     ):




     def __init__(				self ,						a__ ,						a__ = None):
         A__		 =					max_time
         A__		 =					time.time() if initial_timestamp is None else initial_timestamp




     @add_start_docstrings(a__)
     def __call__(				self ,						a__ ,						a__ ,						**a__):
         return time.time() - self.initial_timestamp > self.max_time







class     _UpperCAmelCase			(       A__     ):




     @add_start_docstrings(a__)
     def __call__(				self ,						a__ ,						a__ ,						**a__):
         return any(criteria(a__ ,						a__) for criteria in self)




     @property
     def 		snake_case_		(				self):
         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:
    A__		 =					stopping_criteria.max_length
    A__		 =					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





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
   from PIL import Image



class     _UpperCAmelCase			(       A__     ):
     UpperCamelCase__		    =				'''Salesforce/blip-image-captioning-base'''
     UpperCamelCase__		    =				(
         '''This is a tool that generates a description of an image. It takes an input named `image` which should be the '''
         '''image to caption, and returns a text that contains the description in English.'''
     )
     UpperCamelCase__		    =				'''image_captioner'''
     UpperCamelCase__		    =				AutoModelForVisionaSeq

     UpperCamelCase__		    =				['''image''']
     UpperCamelCase__		    =				['''text''']




     def __init__(				self ,						*a__ ,						**a__):
         requires_backends(self ,						['''vision'''])
         super().__init__(*a__ ,						**a__)




     def 		snake_case_		(				self ,						a__):
         return self.pre_processor(images=a__ ,						return_tensors='''pt''')




     def 		snake_case_		(				self ,						a__):
         return self.model.generate(**a__)




     def 		snake_case_		(				self ,						a__):
         return self.pre_processor.batch_decode(a__ ,						skip_special_tokens=a__)[0].strip()
