
'''simple docstring'''






from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
 import tensorflow as tf

 from ..tf_utils import stable_softmax


if is_torch_available():
 import torch


UpperCAmelCase_       :   Any   =       logging.get_logger(__name__)

@add_end_docstrings(
    A						,	r'\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '						,	)
class  UpperCAmelCase__						(       A ):



    def   lowerCamelCase_  (	self      :       Dict,__A      :       GenericTensor     ):
          if self.framework == "tf":
                _lowerCamelCase				:   Any								=   tf.where(input_ids == self.tokenizer.mask_token_id     ).numpy()
          elif self.framework == "pt":
                _lowerCamelCase				:   int								=   torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=__A     )
          else:
                raise ValueError("Unsupported framework"     )
          return masked_index



    def   lowerCamelCase_  (	self      :       Dict,__A      :       GenericTensor     ):
          _lowerCamelCase				:   List[Any]								=   self.get_masked_index(__A     )
          _lowerCamelCase				:   List[Any]								=   np.prod(masked_index.shape     )
          if numel < 1:
                raise PipelineException(
                    "fill-mask",self.model.base_model_prefix,f'No mask_token ({self.tokenizer.mask_token}) found on the input',)



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       GenericTensor     ):
          if isinstance(__A,__A     ):
                for model_input in model_inputs:
                      self._ensure_exactly_one_mask_token(model_input["input_ids"][0]     )
          else:
                for input_ids in model_inputs["input_ids"]:
                      self._ensure_exactly_one_mask_token(__A     )



    def   lowerCamelCase_  (	self      :       List[str],__A      :       Tuple,__A      :       List[Any]=None,**__A      :       str     ):
          if return_tensors is None:
                _lowerCamelCase				:   Optional[int]								=   self.framework
          _lowerCamelCase				:   List[Any]								=   self.tokenizer(__A,return_tensors=__A     )
          self.ensure_exactly_one_mask_token(__A     )
          return model_inputs



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   Any								=   self.model(**__A     )
          _lowerCamelCase				:   Optional[Any]								=   model_inputs["input_ids"]
          return model_outputs



    def   lowerCamelCase_  (	self      :       List[str],__A      :       int,__A      :       Optional[Any]=5,__A      :       int=None     ):
          # Cap top_k if there are targets
          if target_ids is not None and target_ids.shape[0] < top_k:
                _lowerCamelCase				:   str								=   target_ids.shape[0]
          _lowerCamelCase				:   int								=   model_outputs["input_ids"][0]
          _lowerCamelCase				:   int								=   model_outputs["logits"]

          if self.framework == "tf":
                _lowerCamelCase				:   Any								=   tf.where(input_ids == self.tokenizer.mask_token_id     ).numpy()[:, 0]

                _lowerCamelCase				:   List[Any]								=   outputs.numpy()

                _lowerCamelCase				:   List[str]								=   outputs[0, masked_index, :]
                _lowerCamelCase				:   Dict								=   stable_softmax(__A,axis=-1     )
                if target_ids is not None:
                      _lowerCamelCase				:   Dict								=   tf.gather_nd(tf.squeeze(__A,0     ),target_ids.reshape(-1,1     )     )
                      _lowerCamelCase				:   int								=   tf.expand_dims(__A,0     )

                _lowerCamelCase				:   Tuple								=   tf.math.top_k(__A,k=__A     )
                _lowerCamelCase						,		_lowerCamelCase				:   Union[str, Any]								=   topk.values.numpy(), topk.indices.numpy()
          else:
                _lowerCamelCase				:   List[Any]								=   torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=__A     ).squeeze(-1     )
                # Fill mask pipeline supports only one ${mask_token} per sample

                _lowerCamelCase				:   List[str]								=   outputs[0, masked_index, :]
                _lowerCamelCase				:   Optional[Any]								=   logits.softmax(dim=-1     )
                if target_ids is not None:
                      _lowerCamelCase				:   List[Any]								=   probs[..., target_ids]

                _lowerCamelCase						,		_lowerCamelCase				:   Optional[int]								=   probs.topk(__A     )

          _lowerCamelCase				:   int								=   []
          _lowerCamelCase				:   Tuple								=   values.shape[0] == 1
          for i, (_values, _predictions) in enumerate(zip(values.tolist(),predictions.tolist()     )     ):
                _lowerCamelCase				:   List[Any]								=   []
                for v, p in zip(_values,_predictions     ):
                      # Copy is important since we're going to modify this array in place
                      _lowerCamelCase				:   Optional[Any]								=   input_ids.numpy().copy()
                      if target_ids is not None:
                            _lowerCamelCase				:   List[str]								=   target_ids[p].tolist()

                      _lowerCamelCase				:   Optional[int]								=   p
                      # Filter padding out:
                      _lowerCamelCase				:   Any								=   tokens[np.where(tokens != self.tokenizer.pad_token_id     )]
                      # Originally we skip special tokens to give readable output.
                      # For multi masks though, the other [MASK] would be removed otherwise
                      # making the output look odd, so we add them back
                      _lowerCamelCase				:   str								=   self.tokenizer.decode(__A,skip_special_tokens=__A     )
                      _lowerCamelCase				:   Any								=   {"score": v, "token": p, "token_str": self.tokenizer.decode([p]     ), "sequence": sequence}
                      row.append(__A     )
                result.append(__A     )
          if single_mask:
                return result[0]
          return result



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       Tuple,__A      :       Optional[Any]=None     ):
          if isinstance(__A,__A     ):
                _lowerCamelCase				:   Tuple								=   [targets]
          try:
                _lowerCamelCase				:   Dict								=   self.tokenizer.get_vocab()
          except Exception:
                _lowerCamelCase				:   Optional[int]								=   {}
          _lowerCamelCase				:   List[str]								=   []
          for target in targets:
                _lowerCamelCase				:   Dict								=   vocab.get(__A,__A     )
                if id_ is None:
                      _lowerCamelCase				:   int								=   self.tokenizer(
                          __A,add_special_tokens=__A,return_attention_mask=__A,return_token_type_ids=__A,max_length=1,truncation=__A,)["input_ids"]
                      if len(__A     ) == 0:
                            logger.warning(
                                f'The specified target token `{target}` does not exist in the model vocabulary. '
                                "We cannot replace it with anything meaningful, ignoring it"     )
                            continue
                      _lowerCamelCase				:   List[str]								=   input_ids[0]
                      # XXX: If users encounter this pass
                      # it becomes pretty slow, so let's make sure
                      # The warning enables them to fix the input to
                      # get faster performance.
                      logger.warning(
                          f'The specified target token `{target}` does not exist in the model vocabulary. '
                          f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_     )}`.'     )
                target_ids.append(id_     )
          _lowerCamelCase				:   Any								=   list(set(__A     )     )
          if len(__A     ) == 0:
                raise ValueError("At least one target must be provided when passed."     )
          _lowerCamelCase				:   List[Any]								=   np.array(__A     )
          return target_ids



    def   lowerCamelCase_  (	self      :       str,__A      :       Any=None,__A      :       int=None     ):
          _lowerCamelCase				:   List[str]								=   {}

          if targets is not None:
                _lowerCamelCase				:   Optional[int]								=   self.get_target_ids(__A,__A     )
                _lowerCamelCase				:   Union[str, Any]								=   target_ids

          if top_k is not None:
                _lowerCamelCase				:   Optional[int]								=   top_k

          if self.tokenizer.mask_token_id is None:
                raise PipelineException(
                    "fill-mask",self.model.base_model_prefix,"The tokenizer does not define a `mask_token`."     )
          return {}, {}, postprocess_params



    def __call__(	self      :       int,__A      :       List[str],*__A      :       Dict,**__A      :       List[str]     ):
          _lowerCamelCase				:   List[str]								=   super().__call__(__A,**__A     )
          if isinstance(__A,__A     ) and len(__A     ) == 1:
                return outputs[0]
          return outputs

'''simple docstring'''






import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


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

UpperCAmelCase_       :   Any   =       list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase_       :   str   =       tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class  UpperCAmelCase__						:
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Model type selected in the list: ' + ', '.join(A )} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}						,	)
    lowerCAmelCase_				    =		field(
        default=64						,	metadata={
            'help': (
                'The maximum number of tokens for the question. Questions longer than this will '
                'be truncated to this length.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=30						,	metadata={
            'help': (
                'The maximum length of an answer that can be generated. This is needed because the start '
                'and end predictions are not conditioned on one another.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Overwrite the cached training and evaluation sets'} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
    lowerCAmelCase_				    =		field(
        default=0.0						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=20						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=0						,	metadata={
            'help': (
                'language id of input for language-specific xlm models (see'
                ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
            )
        }						,	)
    lowerCAmelCase_				    =		field(default=1						,	metadata={'help': 'multiple threads for converting example to features'} )


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		'train'
    lowerCAmelCase_				    =		'dev'


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42



    def __init__(	self      :       Optional[int],__A      :       SquadDataTrainingArguments,__A      :       PreTrainedTokenizer,__A      :       Optional[int] = None,__A      :       Union[str, Split] = Split.train,__A      :       Optional[bool] = False,__A      :       Optional[str] = None,__A      :       Optional[str] = "pt",):
          _lowerCamelCase				:   Tuple								=   args
          _lowerCamelCase				:   List[str]								=   is_language_sensitive
          _lowerCamelCase				:   Dict								=   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
          if isinstance(__A,__A     ):
                try:
                      _lowerCamelCase				:   Union[str, Any]								=   Split[mode]
                except KeyError:
                      raise KeyError("mode is not a valid split name"     )
          _lowerCamelCase				:   str								=   mode
          # Load data features from cache or dataset file
          _lowerCamelCase				:   str								=   "v2" if args.version_2_with_negative else "v1"
          _lowerCamelCase				:   Optional[Any]								=   os.path.join(
              cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',)

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          _lowerCamelCase				:   Tuple								=   cached_features_file + ".lock"
          with FileLock(__A     ):
                if os.path.exists(__A     ) and not args.overwrite_cache:
                      _lowerCamelCase				:   int								=   time.time()
                      _lowerCamelCase				:   int								=   torch.load(__A     )

                      # Legacy cache files have only features, while new cache files
                      # will have dataset and examples also.
                      _lowerCamelCase				:   Union[str, Any]								=   self.old_features["features"]
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("dataset",__A     )
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("examples",__A     )
                      logger.info(
                          f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start     )

                      if self.dataset is None or self.examples is None:
                            logger.warning(
                                f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
                                " future run"     )
                else:
                      if mode == Split.dev:
                            _lowerCamelCase				:   Dict								=   self.processor.get_dev_examples(args.data_dir     )
                      else:
                            _lowerCamelCase				:   Dict								=   self.processor.get_train_examples(args.data_dir     )

                      _lowerCamelCase						,		_lowerCamelCase				:   Dict								=   squad_convert_examples_to_features(
                          examples=self.examples,tokenizer=__A,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__A,)

                      _lowerCamelCase				:   List[Any]								=   time.time()
                      torch.save(
                          {"features": self.features, "dataset": self.dataset, "examples": self.examples},__A,)
                      # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                      logger.info(
                          f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'     )



    def __len__(	self      :       Optional[Any]     ):
          return len(self.features     )



    def __getitem__(	self      :       Tuple,__A      :       str     ):
          # Convert to Tensors and build dataset
          _lowerCamelCase				:   List[str]								=   self.features[i]

          _lowerCamelCase				:   List[str]								=   torch.tensor(feature.input_ids,dtype=torch.long     )
          _lowerCamelCase				:   Optional[int]								=   torch.tensor(feature.attention_mask,dtype=torch.long     )
          _lowerCamelCase				:   Union[str, Any]								=   torch.tensor(feature.token_type_ids,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.cls_index,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.p_mask,dtype=torch.float     )
          _lowerCamelCase				:   Tuple								=   torch.tensor(feature.is_impossible,dtype=torch.float     )

          _lowerCamelCase				:   Optional[Any]								=   {
              "input_ids": input_ids,
              "attention_mask": attention_mask,
              "token_type_ids": token_type_ids,
          }

          if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                del inputs["token_type_ids"]

          if self.args.model_type in ["xlnet", "xlm"]:
                inputs.update({"cls_index": cls_index, "p_mask": p_mask}     )
                if self.args.version_2_with_negative:
                      inputs.update({"is_impossible": is_impossible}     )
                if self.is_language_sensitive:
                      inputs.update({"langs": (torch.ones(input_ids.shape,dtype=torch.intaa     ) * self.args.lang_id)}     )

          if self.mode == Split.train:
                _lowerCamelCase				:   List[str]								=   torch.tensor(feature.start_position,dtype=torch.long     )
                _lowerCamelCase				:   Any								=   torch.tensor(feature.end_position,dtype=torch.long     )
                inputs.update({"start_positions": start_positions, "end_positions": end_positions}     )

          return inputs