

import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf



class   lowercase_   (  enum.Enum					):
      UpperCamelCase_      :		Optional[Any]										=    0
      UpperCamelCase_      :		Optional[Any]										=    1
      UpperCamelCase_      :		Union[str, Any]										=    2



@add_end_docstrings(__lowercase					)
class   lowercase_   (  __lowercase					):
      UpperCamelCase_      :		Dict										=    "\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    "



      def __init__(      self				:    List[Any]      , *A__				:    int      , **A__				:    int		)   ->					Dict:
        super().__init__(*A__      , **A__		)
        self.check_model_type(
            TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING		)
        if "prefix" not in self._preprocess_params:
          # This is very specific. The logic is quite complex and needs to be done
          # as a "default".
          # It also defines both some preprocess_kwargs and generate_kwargs
          # which is why we cannot put them in their respective methods.
          _snake_case						=							None
          if self.model.config.prefix is not None:
            _snake_case						=							self.model.config.prefix
          if prefix is None and self.model.__class__.__name__ in [
              "XLNetLMHeadModel",
              "TransfoXLLMHeadModel",
              "TFXLNetLMHeadModel",
              "TFTransfoXLLMHeadModel",
          ]:
            # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
            _snake_case						=							self.XL_PREFIX
          if prefix is not None:
            # Recalculate some generate_kwargs linked to prefix.
            _snake_case,					_snake_case,					_snake_case						=							self._sanitize_parameters(prefix=A__      , **self._forward_params		)
            _snake_case						=							{**self._preprocess_params, **preprocess_params}
            _snake_case						=							{**self._forward_params, **forward_params}



      def 						UpperCamelCase_		(      self				:    int      , A__				:    int=None      , A__				:    int=None      , A__				:    Dict=None      , A__				:    str=None      , A__				:    str=None      , A__				:    Union[str, Any]=None      , A__				:    Union[str, Any]=None      , A__				:    Tuple=None      , **A__				:    Dict      , )   ->					Dict:
        _snake_case						=							{}
        if prefix is not None:
          _snake_case						=							prefix
        if prefix:
          _snake_case						=							self.tokenizer(
              A__      , padding=A__      , add_special_tokens=A__      , return_tensors=self.framework		)
          _snake_case						=							prefix_inputs['''input_ids'''].shape[-1]

        if handle_long_generation is not None:
          if handle_long_generation not in {"hole"}:
            raise ValueError(
                f"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
                ''' [None, \'hole\']'''		)
          _snake_case						=							handle_long_generation

        preprocess_params.update(A__		)
        _snake_case						=							generate_kwargs

        _snake_case						=							{}
        if return_full_text is not None and return_type is None:
          if return_text is not None:
            raise ValueError('''`return_text` is mutually exclusive with `return_full_text`'''		)
          if return_tensors is not None:
            raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`'''		)
          _snake_case						=							ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
        if return_tensors is not None and return_type is None:
          if return_text is not None:
            raise ValueError('''`return_text` is mutually exclusive with `return_tensors`'''		)
          _snake_case						=							ReturnType.TENSORS
        if return_type is not None:
          _snake_case						=							return_type
        if clean_up_tokenization_spaces is not None:
          _snake_case						=							clean_up_tokenization_spaces

        if stop_sequence is not None:
          _snake_case						=							self.tokenizer.encode(A__      , add_special_tokens=A__		)
          if len(A__		) > 1:
            warnings.warn(
                '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of'''
                ''' the stop sequence will be used as the stop sequence string in the interim.'''		)
          _snake_case						=							stop_sequence_ids[0]

        return preprocess_params, forward_params, postprocess_params



      def 						UpperCamelCase_		(      self				:    Optional[Any]      , *A__				:    Union[str, Any]      , **A__				:    Any		)   ->					List[Any]:
        # Parse arguments
        if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
          kwargs.update({'''add_space_before_punct_symbol''': True}		)

        return super()._parse_and_tokenize(*A__      , **A__		)



      def __call__(      self				:    List[str]      , A__				:    Union[str, Any]      , **A__				:    List[str]		)   ->					Tuple:
        return super().__call__(A__      , **A__		)



      def 						UpperCamelCase_		(      self				:    Tuple      , A__				:    List[Any]      , A__				:    Tuple=""      , A__				:    List[Any]=None      , **A__				:    Any		)   ->					Dict:
        _snake_case						=							self.tokenizer(
            prefix + prompt_text      , padding=A__      , add_special_tokens=A__      , return_tensors=self.framework		)
        _snake_case						=							prompt_text

        if handle_long_generation == "hole":
          _snake_case						=							inputs['''input_ids'''].shape[-1]
          if "max_new_tokens" in generate_kwargs:
            _snake_case						=							generate_kwargs['''max_new_tokens''']
          else:
            _snake_case						=							generate_kwargs.get('''max_length'''      , self.model.config.max_length		) - cur_len
            if new_tokens < 0:
              raise ValueError('''We cannot infer how many new tokens are expected'''		)
          if cur_len + new_tokens > self.tokenizer.model_max_length:
            _snake_case						=							self.tokenizer.model_max_length - new_tokens
            if keep_length <= 0:
              raise ValueError(
                  '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the'''
                  ''' models max length'''		)

            _snake_case						=							inputs['''input_ids'''][:, -keep_length:]
            if "attention_mask" in inputs:
              _snake_case						=							inputs['''attention_mask'''][:, -keep_length:]

        return inputs



      def 						UpperCamelCase_		(      self				:    Tuple      , A__				:    str      , **A__				:    int		)   ->					Any:
        _snake_case						=							model_inputs['''input_ids''']
        _snake_case						=							model_inputs.get('''attention_mask'''      , A__		)
        # Allow empty prompts
        if input_ids.shape[1] == 0:
          _snake_case						=							None
          _snake_case						=							None
          _snake_case						=							1
        else:
          _snake_case						=							input_ids.shape[0]
        _snake_case						=							model_inputs.pop('''prompt_text'''		)

        # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
        # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
        _snake_case						=							generate_kwargs.pop('''prefix_length'''      , 0		)
        if prefix_length > 0:
          _snake_case						=							'''max_new_tokens''' in generate_kwargs or (
              '''generation_config''' in generate_kwargs
              and generate_kwargs['''generation_config'''].max_new_tokens is not None
          )
          if not has_max_new_tokens:
            _snake_case						=							generate_kwargs.get('''max_length'''		) or self.model.config.max_length
            generate_kwargs["max_length"] += prefix_length
          _snake_case						=							'''min_new_tokens''' in generate_kwargs or (
              '''generation_config''' in generate_kwargs
              and generate_kwargs['''generation_config'''].min_new_tokens is not None
          )
          if not has_min_new_tokens and "min_length" in generate_kwargs:
            generate_kwargs["min_length"] += prefix_length

        # BS x SL
        _snake_case						=							self.model.generate(input_ids=A__      , attention_mask=A__      , **A__		)
        _snake_case						=							generated_sequence.shape[0]
        if self.framework == "pt":
          _snake_case						=							generated_sequence.reshape(A__      , out_b // in_b      , *generated_sequence.shape[1:]		)
        elif self.framework == "tf":
          _snake_case						=							tf.reshape(A__      , (in_b, out_b // in_b, *generated_sequence.shape[1:])		)
        return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







      def 						UpperCamelCase_		(      self				:    List[Any]      , A__				:    List[Any]      , A__				:    Union[str, Any]=ReturnType.FULL_TEXT      , A__				:    Union[str, Any]=True		)   ->					Optional[Any]:
        _snake_case						=							model_outputs['''generated_sequence'''][0]
        _snake_case						=							model_outputs['''input_ids''']
        _snake_case						=							model_outputs['''prompt_text''']
        _snake_case						=							generated_sequence.numpy().tolist()
        _snake_case						=							[]
        for sequence in generated_sequence:
          if return_type == ReturnType.TENSORS:
            _snake_case						=							{'''generated_token_ids''': sequence}
          elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
            # Decode text
            _snake_case						=							self.tokenizer.decode(
                A__      , skip_special_tokens=A__      , clean_up_tokenization_spaces=A__      , )

            # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
            if input_ids is None:
              _snake_case						=							0
            else:
              _snake_case						=							len(
                  self.tokenizer.decode(
                      input_ids[0]      , skip_special_tokens=A__      , clean_up_tokenization_spaces=A__      , )		)

            if return_type == ReturnType.FULL_TEXT:
              _snake_case						=							prompt_text + text[prompt_length:]
            else:
              _snake_case						=							text[prompt_length:]

            _snake_case						=							{'''generated_text''': all_text}
          records.append(A__		)

        return records




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import VivitImageProcessor



class   lowercase_   (  unittest.TestCase					):



      def __init__(      self				:    Union[str, Any]      , A__				:    int      , A__				:    List[str]=7      , A__				:    Tuple=3      , A__				:    List[str]=10      , A__				:    Optional[int]=18      , A__				:    int=30      , A__				:    Tuple=400      , A__				:    Dict=True      , A__				:    str=None      , A__				:    str=True      , A__				:    List[str]=[0.5, 0.5, 0.5]      , A__				:    int=[0.5, 0.5, 0.5]      , A__				:    List[Any]=None      , )   ->					int:
        _snake_case						=							size if size is not None else {'''shortest_edge''': 18}
        _snake_case						=							crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

        _snake_case						=							parent
        _snake_case						=							batch_size
        _snake_case						=							num_channels
        _snake_case						=							num_frames
        _snake_case						=							image_size
        _snake_case						=							min_resolution
        _snake_case						=							max_resolution
        _snake_case						=							do_resize
        _snake_case						=							size
        _snake_case						=							do_normalize
        _snake_case						=							image_mean
        _snake_case						=							image_std
        _snake_case						=							crop_size







      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					Union[str, Any]:
        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
            "crop_size": self.crop_size,
        }



@require_torch
@require_vision
class   lowercase_   (  __lowercase       ,							unittest.TestCase					):
      UpperCamelCase_      :		Tuple										=    VivitImageProcessor if is_vision_available() else None



      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					List[str]:
        _snake_case						=							VivitImageProcessingTester(self		)



      @property
      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					Optional[Any]:
        return self.image_processor_tester.prepare_image_processor_dict()



      def 						UpperCamelCase_		(      self				:    Optional[int]		)   ->					Optional[Any]:
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(A__      , '''image_mean'''		)		)
        self.assertTrue(hasattr(A__      , '''image_std'''		)		)
        self.assertTrue(hasattr(A__      , '''do_normalize'''		)		)
        self.assertTrue(hasattr(A__      , '''do_resize'''		)		)
        self.assertTrue(hasattr(A__      , '''do_center_crop'''		)		)
        self.assertTrue(hasattr(A__      , '''size'''		)		)



      def 						UpperCamelCase_		(      self				:    int		)   ->					List[Any]:
        _snake_case						=							self.image_processing_class.from_dict(self.image_processor_dict		)
        self.assertEqual(image_processor.size      , {'''shortest_edge''': 18}		)
        self.assertEqual(image_processor.crop_size      , {'''height''': 18, '''width''': 18}		)

        _snake_case						=							self.image_processing_class.from_dict(self.image_processor_dict      , size=42      , crop_size=84		)
        self.assertEqual(image_processor.size      , {'''shortest_edge''': 42}		)
        self.assertEqual(image_processor.crop_size      , {'''height''': 84, '''width''': 84}		)



      def 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Optional[Any]:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random PIL videos
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , Image.Image		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )



      def 						UpperCamelCase_		(      self				:    Any		)   ->					List[str]:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random numpy tensors
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__      , numpify=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , np.ndarray		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )







      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					int:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random PyTorch tensors
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__      , torchify=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , torch.Tensor		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

