


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 		__magic_name__						(enum.Enum				):





     '''simple docstring'''



     __lowercase				:							Dict	   =       0
     __lowercase				:							Tuple	   =       1
     __lowercase				:							List[Any]	   =       2




@add_end_docstrings(snake_case_				)
class 		__magic_name__						(snake_case_				):





     '''simple docstring'''



     __lowercase				:							List[Any]	   =       '\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:Dict     ,		*_a:int     ,		**_a: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 	SCREAMING_SNAKE_CASE__						(					self:Any     ,		_a:str=None     ,		_a:Tuple=None     ,		_a:Optional[Any]=None     ,		_a:str=None     ,		_a:Union[str, Any]=None     ,		_a:Union[str, Any]=None     ,		_a:str=None     ,		_a:int=None     ,		**_a:int     ,		):
       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 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		*_a:List[str]     ,		**_a:Optional[int]   ):
       # 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:str     ,		**_a:int   ):
       return super().__call__(_a     ,		**_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]     ,		_a:int     ,		_a:int=""     ,		_a:int=None     ,		**_a:int   ):
       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 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:List[str]     ,		**_a: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 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:Tuple     ,		_a:Union[str, Any]=ReturnType.FULL_TEXT     ,		_a:Optional[int]=True   ):
       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 json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402
class 		__magic_name__						(unittest.TestCase				):





     '''simple docstring'''



     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]   ):
       snake_case__						= 0

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[Any]   ):
       snake_case__						= AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''   )
       self.assertIsInstance(_a     ,		_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:str   ):
       with tempfile.TemporaryDirectory() as tmpdirname:
         snake_case__						= Path(_a   ) / '''preprocessor_config.json'''
         snake_case__						= Path(_a   ) / '''config.json'''
         json.dump(
             {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,		open(_a     ,		'''w'''   )     ,		)
         json.dump({'''model_type''': '''clip'''}     ,		open(_a     ,		'''w'''   )   )

         snake_case__						= AutoImageProcessor.from_pretrained(_a   )
         self.assertIsInstance(_a     ,		_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       # Ensure we can load the image processor from the feature extractor config
       with tempfile.TemporaryDirectory() as tmpdirname:
         snake_case__						= Path(_a   ) / '''preprocessor_config.json'''
         snake_case__						= Path(_a   ) / '''config.json'''
         json.dump(
             {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}     ,		open(_a     ,		'''w'''   )     ,		)
         json.dump({'''model_type''': '''clip'''}     ,		open(_a     ,		'''w'''   )   )

         snake_case__						= AutoImageProcessor.from_pretrained(_a   )
         self.assertIsInstance(_a     ,		_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       with tempfile.TemporaryDirectory() as tmpdirname:
         snake_case__						= CLIPConfig()

         # Create a dummy config file with image_proceesor_type
         snake_case__						= Path(_a   ) / '''preprocessor_config.json'''
         snake_case__						= Path(_a   ) / '''config.json'''
         json.dump(
             {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,		open(_a     ,		'''w'''   )     ,		)
         json.dump({'''model_type''': '''clip'''}     ,		open(_a     ,		'''w'''   )   )

         # remove image_processor_type to make sure config.json alone is enough to load image processor locally
         snake_case__						= AutoImageProcessor.from_pretrained(_a   ).to_dict()

         config_dict.pop('''image_processor_type'''   )
         snake_case__						= CLIPImageProcessor(**_a   )

         # save in new folder
         model_config.save_pretrained(_a   )
         config.save_pretrained(_a   )

         snake_case__						= AutoImageProcessor.from_pretrained(_a   )

         # make sure private variable is not incorrectly saved
         snake_case__						= json.loads(config.to_json_string()   )
         self.assertTrue('''_processor_class''' not in dict_as_saved   )

       self.assertIsInstance(_a     ,		_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]   ):
       with tempfile.TemporaryDirectory() as tmpdirname:
         snake_case__						= Path(_a   ) / '''preprocessor_config.json'''
         json.dump(
             {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,		open(_a     ,		'''w'''   )     ,		)

         snake_case__						= AutoImageProcessor.from_pretrained(_a   )
         self.assertIsInstance(_a     ,		_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       with self.assertRaisesRegex(
           _a     ,		'''clip-base is not a local folder and is not a valid model identifier'''   ):
         snake_case__						= AutoImageProcessor.from_pretrained('''clip-base'''   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]   ):
       with self.assertRaisesRegex(
           _a     ,		r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''   ):
         snake_case__						= AutoImageProcessor.from_pretrained(_a     ,		revision='''aaaaaa'''   )

     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]   ):
       with self.assertRaisesRegex(
           _a     ,		'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''     ,		):
         snake_case__						= AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       # If remote code is not set, we will time out when asking whether to load the model.
       with self.assertRaises(_a   ):
         snake_case__						= AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''   )
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(_a   ):
         snake_case__						= AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_image_processor'''     ,		trust_remote_code=_a   )

       snake_case__						= AutoImageProcessor.from_pretrained(
           '''hf-internal-testing/test_dynamic_image_processor'''     ,		trust_remote_code=_a   )
       self.assertEqual(image_processor.__class__.__name__     ,		'''NewImageProcessor'''   )

       # Test image processor can be reloaded.
       with tempfile.TemporaryDirectory() as tmp_dir:
         image_processor.save_pretrained(_a   )
         snake_case__						= AutoImageProcessor.from_pretrained(_a     ,		trust_remote_code=_a   )
       self.assertEqual(reloaded_image_processor.__class__.__name__     ,		'''NewImageProcessor'''   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       try:
         AutoConfig.register('''custom'''     ,		_a   )
         AutoImageProcessor.register(_a     ,		_a   )
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(_a   ):
           AutoImageProcessor.register(_a     ,		_a   )

         with tempfile.TemporaryDirectory() as tmpdirname:
           snake_case__						= Path(_a   ) / '''preprocessor_config.json'''
           snake_case__						= Path(_a   ) / '''config.json'''
           json.dump(
               {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}     ,		open(_a     ,		'''w'''   )     ,		)
           json.dump({'''model_type''': '''clip'''}     ,		open(_a     ,		'''w'''   )   )

           snake_case__						= CustomImageProcessor.from_pretrained(_a   )

         # Now that the config is registered, it can be used as any other config with the auto-API
         with tempfile.TemporaryDirectory() as tmp_dir:
           image_processor.save_pretrained(_a   )
           snake_case__						= AutoImageProcessor.from_pretrained(_a   )
           self.assertIsInstance(_a     ,		_a   )

       finally:
         if "custom" in CONFIG_MAPPING._extra_content:
           del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
           del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]







     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       class 		__magic_name__						(snake_case_				):





            '''simple docstring'''



            __lowercase				:							List[str]	   =       True

       try:
         AutoConfig.register('''custom'''     ,		_a   )
         AutoImageProcessor.register(_a     ,		_a   )
         # If remote code is not set, the default is to use local
         snake_case__						= AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''   )
         self.assertEqual(image_processor.__class__.__name__     ,		'''NewImageProcessor'''   )
         self.assertTrue(image_processor.is_local   )

         # If remote code is disabled, we load the local one.
         snake_case__						= AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_image_processor'''     ,		trust_remote_code=_a   )
         self.assertEqual(image_processor.__class__.__name__     ,		'''NewImageProcessor'''   )
         self.assertTrue(image_processor.is_local   )

         # If remote is enabled, we load from the Hub
         snake_case__						= AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_image_processor'''     ,		trust_remote_code=_a   )
         self.assertEqual(image_processor.__class__.__name__     ,		'''NewImageProcessor'''   )
         self.assertTrue(not hasattr(_a     ,		'''is_local'''   )   )

       finally:
         if "custom" in CONFIG_MAPPING._extra_content:
           del CONFIG_MAPPING._extra_content["custom"]
         if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
           del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]

