
'''simple docstring'''







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





  """simple docstring"""

  __UpperCAmelCase				:				Dict   =					0
  __UpperCAmelCase				:				Union[str, Any]   =					1
  __UpperCAmelCase				:				Tuple   =					2







@add_end_docstrings(a_	)
class UpperCAmelCase__	( a_	):





  """simple docstring"""

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


  def __init__(		self      :     Optional[Any]							,*_a      :     Any							,**_a      :     Any       ):


     '''simple docstring'''






     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.
        _a				:	Dict			=   None
        if self.model.config.prefix is not None:
           _a				:	Optional[int]			=   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.
           _a				:	int			=   self.XL_PREFIX
        if prefix is not None:
           # Recalculate some generate_kwargs linked to prefix.
           _a				:	Dict			=   self._sanitize_parameters(prefix=_a							,**self._forward_params       )
           _a				:	str			=   {**self._preprocess_params, **preprocess_params}
           _a				:	Any			=   {**self._forward_params, **forward_params}


  def   __lowercase		(		self      :     Tuple							,_a      :     Union[str, Any]=None							,_a      :     Union[str, Any]=None							,_a      :     int=None							,_a      :     Optional[Any]=None							,_a      :     Tuple=None							,_a      :     Optional[int]=None							,_a      :     Optional[Any]=None							,_a      :     int=None							,**_a      :     Optional[Any]							,):


     '''simple docstring'''






     _a				:	str			=   {}
     if prefix is not None:
        _a				:	Tuple			=   prefix
     if prefix:
        _a				:	Dict			=   self.tokenizer(
            _a							,padding=_a							,add_special_tokens=_a							,return_tensors=self.framework       )
        _a				:	List[Any]			=   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\']'       )
        _a				:	List[Any]			=   handle_long_generation

     preprocess_params.update(_a       )
     _a				:	Dict			=   generate_kwargs

     _a				:	int			=   {}
     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`'       )
        _a				:	Any			=   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`'       )
        _a				:	Tuple			=   ReturnType.TENSORS
     if return_type is not None:
        _a				:	Any			=   return_type
     if clean_up_tokenization_spaces is not None:
        _a				:	int			=   clean_up_tokenization_spaces

     if stop_sequence is not None:
        _a				:	Tuple			=   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.'       )
        _a				:	int			=   stop_sequence_ids[0]

     return preprocess_params, forward_params, postprocess_params


  def   __lowercase		(		self      :     Any							,*_a      :     Dict							,**_a      :     Any       ):


     '''simple docstring'''






     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      :     str							,_a      :     Dict							,**_a      :     List[str]       ):


     '''simple docstring'''






     return super().__call__(_a							,**_a       )


  def   __lowercase		(		self      :     List[str]							,_a      :     Optional[Any]							,_a      :     Any=""							,_a      :     List[Any]=None							,**_a      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	int			=   self.tokenizer(
         prefix + prompt_text							,padding=_a							,add_special_tokens=_a							,return_tensors=self.framework       )
     _a				:	List[str]			=   prompt_text

     if handle_long_generation == "hole":
        _a				:	Any			=   inputs["input_ids"].shape[-1]
        if "max_new_tokens" in generate_kwargs:
           _a				:	List[Any]			=   generate_kwargs["max_new_tokens"]
        else:
           _a				:	Any			=   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:
           _a				:	List[str]			=   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'       )

           _a				:	Optional[int]			=   inputs["input_ids"][:, -keep_length:]
           if "attention_mask" in inputs:
              _a				:	Tuple			=   inputs["attention_mask"][:, -keep_length:]

     return inputs


  def   __lowercase		(		self      :     int							,_a      :     int							,**_a      :     Union[str, Any]       ):


     '''simple docstring'''






     _a				:	Any			=   model_inputs["input_ids"]
     _a				:	List[Any]			=   model_inputs.get('attention_mask'							,_a       )
     # Allow empty prompts
     if input_ids.shape[1] == 0:
        _a				:	Dict			=   None
        _a				:	Dict			=   None
        _a				:	Union[str, Any]			=   1
     else:
        _a				:	Dict			=   input_ids.shape[0]
     _a				:	Union[str, Any]			=   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.
     _a				:	str			=   generate_kwargs.pop('prefix_length'							,0       )
     if prefix_length > 0:
        _a				:	Optional[int]			=   "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:
           _a				:	List[str]			=   generate_kwargs.get('max_length'       ) or self.model.config.max_length
           generate_kwargs["max_length"] += prefix_length
        _a				:	str			=   "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
     _a				:	Tuple			=   self.model.generate(input_ids=_a							,attention_mask=_a							,**_a       )
     _a				:	List[str]			=   generated_sequence.shape[0]
     if self.framework == "pt":
        _a				:	List[str]			=   generated_sequence.reshape(_a							,out_b // in_b							,*generated_sequence.shape[1:]       )
     elif self.framework == "tf":
        _a				:	Dict			=   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   __lowercase		(		self      :     Tuple							,_a      :     Tuple							,_a      :     Any=ReturnType.FULL_TEXT							,_a      :     List[Any]=True       ):


     '''simple docstring'''






     _a				:	List[str]			=   model_outputs["generated_sequence"][0]
     _a				:	List[str]			=   model_outputs["input_ids"]
     _a				:	Tuple			=   model_outputs["prompt_text"]
     _a				:	Optional[Any]			=   generated_sequence.numpy().tolist()
     _a				:	int			=   []
     for sequence in generated_sequence:
        if return_type == ReturnType.TENSORS:
           _a				:	int			=   {"generated_token_ids": sequence}
        elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
           # Decode text
           _a				:	Dict			=   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:
              _a				:	List[Any]			=   0
           else:
              _a				:	Optional[int]			=   len(
                  self.tokenizer.decode(
                      input_ids[0]							,skip_special_tokens=_a							,clean_up_tokenization_spaces=_a							,)       )

           if return_type == ReturnType.FULL_TEXT:
              _a				:	Union[str, Any]			=   prompt_text + text[prompt_length:]
           else:
              _a				:	Tuple			=   text[prompt_length:]

           _a				:	Dict			=   {"generated_text": all_text}
        records.append(_a       )

     return records





"""simple docstring"""




# 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.
import re

from ..utils import cached_file


# docstyle-ignore
_A			:       Optional[int]   		=       """
Human: <<task>>

Assistant: """


_A			:       List[Any]   		=       """huggingface-tools/default-prompts"""
_A			:       Optional[int]   		=       {"""chat""": """chat_prompt_template.txt""", """run""": """run_prompt_template.txt"""}


def   __magic_name__	(      __snake_case				:       int     , __snake_case				:       List[Any]     , __snake_case				:       Dict="run"  ) ->				Union[str, Any]:
       if prompt_or_repo_id is None:
              lowercase    :				List[Any]       		=							DEFAULT_PROMPTS_REPO

       # prompt is considered a repo ID when it does not contain any kind of space
       if re.search("\\s"     , __snake_case  ) is not None:
              return prompt_or_repo_id

       lowercase    :				Optional[int]       		=							cached_file(
           __snake_case     , PROMPT_FILES[mode]     , repo_type="dataset"     , user_agent={"agent": agent_name}  )
       with open(__snake_case     , "r"     , encoding="utf-8"  ) as f:
              return f.read()


