




'''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   _a							(		enum.Enum				):
     SCREAMING_SNAKE_CASE_				:       Tuple       							=		0
     SCREAMING_SNAKE_CASE_				:       Optional[int]       							=		1
     SCREAMING_SNAKE_CASE_				:       int       							=		2







@add_end_docstrings(__lowerCAmelCase				)
class   _a							(		__lowerCAmelCase				):
     SCREAMING_SNAKE_CASE_				:       str       							=		"""
    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   ,*_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )				->     Optional[Any]:
          super().__init__(*_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )
          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=_SCREAMING_SNAKE_CASE   ,**self._forward_params       )
                    _snake_case				= {**self._preprocess_params, **preprocess_params}
                    _snake_case				= {**self._forward_params, **forward_params}






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,_SCREAMING_SNAKE_CASE=None   ,**_SCREAMING_SNAKE_CASE   ,)				->     Union[str, Any]:
          _snake_case				= {}
          if prefix is not None:
               _snake_case				= prefix
          if prefix:
               _snake_case				= self.tokenizer(
                   _SCREAMING_SNAKE_CASE   ,padding=_SCREAMING_SNAKE_CASE   ,add_special_tokens=_SCREAMING_SNAKE_CASE   ,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(_SCREAMING_SNAKE_CASE       )
          _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(_SCREAMING_SNAKE_CASE   ,add_special_tokens=_SCREAMING_SNAKE_CASE       )
               if len(_SCREAMING_SNAKE_CASE       ) > 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 							_lowercase      (					self   ,*_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )				->     Tuple:
          # Parse arguments
          if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
               kwargs.update({"add_space_before_punct_symbol": True}       )

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






     def __call__(					self   ,_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )				->     str:
          return super().__call__(_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE=""   ,_SCREAMING_SNAKE_CASE=None   ,**_SCREAMING_SNAKE_CASE       )				->     List[str]:
          _snake_case				= self.tokenizer(
              prefix + prompt_text   ,padding=_SCREAMING_SNAKE_CASE   ,add_special_tokens=_SCREAMING_SNAKE_CASE   ,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 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )				->     Union[str, Any]:
          _snake_case				= model_inputs["input_ids"]
          _snake_case				= model_inputs.get("attention_mask"   ,_SCREAMING_SNAKE_CASE       )
          # 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=_SCREAMING_SNAKE_CASE   ,attention_mask=_SCREAMING_SNAKE_CASE   ,**_SCREAMING_SNAKE_CASE       )
          _snake_case				= generated_sequence.shape[0]
          if self.framework == "pt":
               _snake_case				= generated_sequence.reshape(_SCREAMING_SNAKE_CASE   ,out_b // in_b   ,*generated_sequence.shape[1:]       )
          elif self.framework == "tf":
               _snake_case				= tf.reshape(_SCREAMING_SNAKE_CASE   ,(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   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT   ,_SCREAMING_SNAKE_CASE=True       )				->     Dict:
          _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(
                        _SCREAMING_SNAKE_CASE   ,skip_special_tokens=_SCREAMING_SNAKE_CASE   ,clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE   ,)

                    # 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=_SCREAMING_SNAKE_CASE   ,clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE   ,)       )

                    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(_SCREAMING_SNAKE_CASE       )

          return records








'''simple docstring'''





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_		:     Optional[Any]          =		logging.get_logger(__name__)

UpperCamelCase_		:     Any          =		{
    '''microsoft/unispeech-sat-base-100h-libri-ft''': (
        '''https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'''
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}

class   _a							(		__lowerCAmelCase				):
     SCREAMING_SNAKE_CASE_				:       str       							=		"""unispeech-sat"""






     def __init__(					self   ,_SCREAMING_SNAKE_CASE=32   ,_SCREAMING_SNAKE_CASE=768   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=3_072   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0_2   ,_SCREAMING_SNAKE_CASE=1e-5   ,_SCREAMING_SNAKE_CASE="group"   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512)   ,_SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2)   ,_SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2)   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=128   ,_SCREAMING_SNAKE_CASE=16   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=True   ,_SCREAMING_SNAKE_CASE=0.0_5   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=320   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=100   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE="mean"   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 1_500)   ,_SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=512   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=1   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=504   ,**_SCREAMING_SNAKE_CASE   ,)				->     Any:
          super().__init__(**_SCREAMING_SNAKE_CASE   ,pad_token_id=_SCREAMING_SNAKE_CASE   ,bos_token_id=_SCREAMING_SNAKE_CASE   ,eos_token_id=_SCREAMING_SNAKE_CASE       )
          _snake_case				= hidden_size
          _snake_case				= feat_extract_norm
          _snake_case				= feat_extract_activation
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= conv_bias
          _snake_case				= num_conv_pos_embeddings
          _snake_case				= num_conv_pos_embedding_groups
          _snake_case				= len(self.conv_dim       )
          _snake_case				= num_hidden_layers
          _snake_case				= intermediate_size
          _snake_case				= hidden_act
          _snake_case				= num_attention_heads
          _snake_case				= hidden_dropout
          _snake_case				= attention_dropout
          _snake_case				= activation_dropout
          _snake_case				= feat_proj_dropout
          _snake_case				= final_dropout
          _snake_case				= layerdrop
          _snake_case				= layer_norm_eps
          _snake_case				= initializer_range
          _snake_case				= vocab_size
          _snake_case				= num_clusters
          _snake_case				= do_stable_layer_norm
          _snake_case				= use_weighted_layer_sum

          if (
              (len(self.conv_stride       ) != self.num_feat_extract_layers)
              or (len(self.conv_kernel       ) != self.num_feat_extract_layers)
              or (len(self.conv_dim       ) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
                   " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
                   f""" {len(self.conv_dim       )}`, `len(config.conv_stride) = {len(self.conv_stride       )}`,"""
                   f""" `len(config.conv_kernel) = {len(self.conv_kernel       )}`."""       )

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          _snake_case				= apply_spec_augment
          _snake_case				= mask_time_prob
          _snake_case				= mask_time_length
          _snake_case				= mask_time_min_masks
          _snake_case				= mask_feature_prob
          _snake_case				= mask_feature_length
          _snake_case				= mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          _snake_case				= num_codevectors_per_group
          _snake_case				= num_codevector_groups
          _snake_case				= contrastive_logits_temperature
          _snake_case				= feat_quantizer_dropout
          _snake_case				= num_negatives
          _snake_case				= codevector_dim
          _snake_case				= proj_codevector_dim
          _snake_case				= diversity_loss_weight

          # ctc loss
          _snake_case				= ctc_loss_reduction
          _snake_case				= ctc_zero_infinity

          # SequenceClassification-specific parameter. Feel free to ignore for other classes.
          _snake_case				= classifier_proj_size

          # XVector-specific parameters. Feel free to ignore for other classes.
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= xvector_output_dim






     @property
     def 							_lowercase      (					self       )				->     List[str]:
          return functools.reduce(operator.mul   ,self.conv_stride   ,1       )


