

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


lowercase_			=  logging.get_logger(__name__)


@add_end_docstrings(
    __lowercase   ,							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 			A						(							__lowercase			):







    """simple docstring"""





    def 						snake_case__					(				self			:	int,lowercase_			:	int		)->   np.ndarray:





         '''simple docstring'''







         if self.framework == "tf":
              A__   				=       tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
         elif self.framework == "pt":
              A__   				=       torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=_a		)
         else:
              raise ValueError('Unsupported framework'		)
         return masked_index


    def 						snake_case__					(				self			:	List[Any],lowercase_			:	Dict		)->   np.ndarray:





         '''simple docstring'''







         A__   				=       self.get_masked_index(_a		)
         A__   				=       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 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	List[str]		)->   Optional[int]:





         '''simple docstring'''







         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 						snake_case__					(				self			:	Optional[Any],lowercase_			:	List[Any],lowercase_			:	Dict=None,**lowercase_			:	int		)->   Dict[str, GenericTensor]:





         '''simple docstring'''







         if return_tensors is None:
              A__   				=       self.framework
         A__   				=       self.tokenizer(_a,return_tensors=_a		)
         self.ensure_exactly_one_mask_token(_a		)
         return model_inputs


    def 						snake_case__					(				self			:	Optional[int],lowercase_			:	str		)->   Optional[Any]:





         '''simple docstring'''







         A__   				=       self.model(**_a		)
         A__   				=       model_inputs['''input_ids''']
         return model_outputs


    def 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	Any,lowercase_			:	Dict=5,lowercase_			:	int=None		)->   str:





         '''simple docstring'''







         if target_ids is not None and target_ids.shape[0] < top_k:
              A__   				=       target_ids.shape[0]
         A__   				=       model_outputs['''input_ids'''][0]
         A__   				=       model_outputs['''logits''']

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

              A__   				=       outputs.numpy()

              A__   				=       outputs[0, masked_index, :]
              A__   				=       stable_softmax(_a,axis=-1		)
              if target_ids is not None:
                   A__   				=       tf.gather_nd(tf.squeeze(_a,0		),target_ids.reshape(-1,1		)		)
                   A__   				=       tf.expand_dims(_a,0		)

              A__   				=       tf.math.top_k(_a,k=_a		)
              A__   				=       topk.values.numpy(), topk.indices.numpy()
         else:
              A__   				=       torch.nonzero(input_ids == self.tokenizer.mask_token_id,as_tuple=_a		).squeeze(-1		)
              # Fill mask pipeline supports only one ${mask_token} per sample

              A__   				=       outputs[0, masked_index, :]
              A__   				=       logits.softmax(dim=-1		)
              if target_ids is not None:
                   A__   				=       probs[..., target_ids]

              A__   				=       probs.topk(_a		)

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

                   A__   				=       p
                   # Filter padding out:
                   A__   				=       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
                   A__   				=       self.tokenizer.decode(_a,skip_special_tokens=_a		)
                   A__   				=       {'''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 						snake_case__					(				self			:	Tuple,lowercase_			:	Union[str, Any],lowercase_			:	List[Any]=None		)->   Dict:





         '''simple docstring'''







         if isinstance(_a,_a		):
              A__   				=       [targets]
         try:
              A__   				=       self.tokenizer.get_vocab()
         except Exception:
              A__   				=       {}
         A__   				=       []
         for target in targets:
              A__   				=       vocab.get(_a,_a		)
              if id_ is None:
                   A__   				=       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
                   A__   				=       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_		)
         A__   				=       list(set(_a		)		)
         if len(_a		) == 0:
              raise ValueError('At least one target must be provided when passed.'		)
         A__   				=       np.array(_a		)
         return target_ids


    def 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	List[Any]=None,lowercase_			:	str=None		)->   Tuple:





         '''simple docstring'''







         A__   				=       {}

         if targets is not None:
              A__   				=       self.get_target_ids(_a,_a		)
              A__   				=       target_ids

         if top_k is not None:
              A__   				=       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			:	str,lowercase_			:	Tuple,*lowercase_			:	Any,**lowercase_			:	Dict		)->   int:





         '''simple docstring'''







         A__   				=       super().__call__(_a,**_a		)
         if isinstance(_a,_a		) and len(_a		) == 1:
              return outputs[0]
         return outputs




import unittest

from transformers import LiltConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         LiltForQuestionAnswering,
         LiltForSequenceClassification,
         LiltForTokenClassification,
         LiltModel,
     )
     from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST


class 			A						:







    """simple docstring"""





    def __init__(				self			:	Any,lowercase_			:	Optional[int],lowercase_			:	Optional[int]=1_3,lowercase_			:	int=7,lowercase_			:	List[str]=True,lowercase_			:	str=True,lowercase_			:	List[str]=True,lowercase_			:	Optional[Any]=True,lowercase_			:	Dict=9_9,lowercase_			:	Dict=2_4,lowercase_			:	Union[str, Any]=2,lowercase_			:	str=6,lowercase_			:	Dict=3_7,lowercase_			:	Optional[Any]="gelu",lowercase_			:	Any=0.1,lowercase_			:	Any=0.1,lowercase_			:	Any=5_1_2,lowercase_			:	Dict=1_6,lowercase_			:	List[str]=2,lowercase_			:	Dict=0.02,lowercase_			:	Any=3,lowercase_			:	Dict=None,lowercase_			:	List[str]=1_0_0_0,)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       parent
        A__   				=       batch_size
        A__   				=       seq_length
        A__   				=       is_training
        A__   				=       use_input_mask
        A__   				=       use_token_type_ids
        A__   				=       use_labels
        A__   				=       vocab_size
        A__   				=       hidden_size
        A__   				=       num_hidden_layers
        A__   				=       num_attention_heads
        A__   				=       intermediate_size
        A__   				=       hidden_act
        A__   				=       hidden_dropout_prob
        A__   				=       attention_probs_dropout_prob
        A__   				=       max_position_embeddings
        A__   				=       type_vocab_size
        A__   				=       type_sequence_label_size
        A__   				=       initializer_range
        A__   				=       num_labels
        A__   				=       scope
        A__   				=       range_bbox


    def 						snake_case__					(				self			:	List[Any]		)->   Tuple:





        '''simple docstring'''







        A__   				=       ids_tensor([self.batch_size, self.seq_length],self.vocab_size		)

        A__   				=       ids_tensor([self.batch_size, self.seq_length, 4],self.range_bbox		)
        # Ensure that bbox is legal
        for i in range(bbox.shape[0]		):
            for j in range(bbox.shape[1]		):
                if bbox[i, j, 3] < bbox[i, j, 1]:
                    A__   				=       bbox[i, j, 3]
                    A__   				=       bbox[i, j, 1]
                    A__   				=       t
                if bbox[i, j, 2] < bbox[i, j, 0]:
                    A__   				=       bbox[i, j, 2]
                    A__   				=       bbox[i, j, 0]
                    A__   				=       t

        A__   				=       None
        if self.use_input_mask:
            A__   				=       ids_tensor([self.batch_size, self.seq_length],vocab_size=2		)

        A__   				=       None
        if self.use_token_type_ids:
            A__   				=       ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size		)

        A__   				=       None
        A__   				=       None
        if self.use_labels:
            A__   				=       ids_tensor([self.batch_size],self.type_sequence_label_size		)
            A__   				=       ids_tensor([self.batch_size, self.seq_length],self.num_labels		)

        A__   				=       self.get_config()

        return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels


    def 						snake_case__					(				self			:	Dict		)->   int:





        '''simple docstring'''







        return LiltConfig(
            vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,)


    def 						snake_case__					(				self			:	Optional[Any],lowercase_			:	Tuple,lowercase_			:	str,lowercase_			:	Optional[int],lowercase_			:	Optional[Any],lowercase_			:	str,lowercase_			:	List[str],lowercase_			:	Tuple,)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       LiltModel(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__   				=       model(lowercase_,bbox=lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_,bbox=lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_,bbox=lowercase_		)

        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)		)
        self.parent.assertEqual(result.pooler_output.shape,(self.batch_size, self.hidden_size)		)


    def 						snake_case__					(				self			:	Any,lowercase_			:	Dict,lowercase_			:	List[Any],lowercase_			:	List[str],lowercase_			:	Optional[int],lowercase_			:	Optional[int],lowercase_			:	Optional[int],lowercase_			:	List[Any],)->   List[str]:





        '''simple docstring'''







        A__   				=       self.num_labels
        A__   				=       LiltForTokenClassification(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__   				=       model(
            lowercase_,bbox=lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_,labels=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)		)


    def 						snake_case__					(				self			:	int,lowercase_			:	Union[str, Any],lowercase_			:	int,lowercase_			:	Tuple,lowercase_			:	Any,lowercase_			:	Optional[int],lowercase_			:	Tuple,lowercase_			:	List[str],)->   Any:





        '''simple docstring'''







        A__   				=       LiltForQuestionAnswering(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__   				=       model(
            lowercase_,bbox=lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_,start_positions=lowercase_,end_positions=lowercase_,)
        self.parent.assertEqual(result.start_logits.shape,(self.batch_size, self.seq_length)		)
        self.parent.assertEqual(result.end_logits.shape,(self.batch_size, self.seq_length)		)


    def 						snake_case__					(				self			:	Optional[int]		)->   Tuple:





        '''simple docstring'''







        A__   				=       self.prepare_config_and_inputs()
        (
            (
            A__
        )				,						(
            A__
        )				,						(
            A__
        )				,						(
            A__
        )				,						(
            A__
        )				,						(
            A__
        )				,						(
            A__
        )				,						
        )   				=       config_and_inputs
        A__   				=       {
            'input_ids': input_ids,
            'bbox': bbox,
            'token_type_ids': token_type_ids,
            'attention_mask': input_mask,
        }
        return config, inputs_dict




@require_torch
class 			A						(							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							unittest.TestCase			):







    """simple docstring"""





    lowerCamelCase		     =							(
        (
            LiltModel,
            LiltForSequenceClassification,
            LiltForTokenClassification,
            LiltForQuestionAnswering,
        )
        if is_torch_available()
        else ()
    )
    lowerCamelCase		     =							(
        {
            'feature-extraction': LiltModel,
            'question-answering': LiltForQuestionAnswering,
            'text-classification': LiltForSequenceClassification,
            'token-classification': LiltForTokenClassification,
            'zero-shot': LiltForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    lowerCamelCase		     =							False
    lowerCamelCase		     =							False


    def 						snake_case__					(				self			:	List[str],lowercase_			:	int,lowercase_			:	List[str],lowercase_			:	str,lowercase_			:	Optional[Any],lowercase_			:	Optional[Any]		)->   Any:





        '''simple docstring'''







        return True


    def 						snake_case__					(				self			:	int		)->   Tuple:





        '''simple docstring'''







        A__   				=       LiltModelTester(self		)
        A__   				=       ConfigTester(self,config_class=lowercase_,hidden_size=3_7		)


    def 						snake_case__					(				self			:	List[Any]		)->   Optional[int]:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    def 						snake_case__					(				self			:	Dict		)->   Union[str, Any]:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase_		)


    def 						snake_case__					(				self			:	Union[str, Any]		)->   Dict:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
            A__   				=       type
            self.model_tester.create_and_check_model(*lowercase_		)


    def 						snake_case__					(				self			:	str		)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase_		)


    def 						snake_case__					(				self			:	List[Any]		)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowercase_		)


    @slow
    def 						snake_case__					(				self			:	List[Any]		)->   int:





        '''simple docstring'''







        for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A__   				=       LiltModel.from_pretrained(lowercase_		)
            self.assertIsNotNone(lowercase_		)




@require_torch
@slow
class 			A						(							unittest.TestCase			):







    """simple docstring"""





    def 						snake_case__					(				self			:	List[Any]		)->   Dict:





        '''simple docstring'''







        A__   				=       LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base'		).to(lowercase_		)

        A__   				=       torch.tensor([[1, 2]],device=lowercase_		)
        A__   				=       torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]],device=lowercase_		)

        # forward pass
        with torch.no_grad():
            A__   				=       model(input_ids=lowercase_,bbox=lowercase_		)

        A__   				=       torch.Size([1, 2, 7_6_8]		)
        A__   				=       torch.tensor(
            [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]],device=lowercase_,)

        self.assertTrue(outputs.last_hidden_state.shape,lowercase_		)
        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3],lowercase_,atol=1E-3		)		)

