





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


snake_case 				=       logging.get_logger(__name__)





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

    '''					,	)
class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	GenericTensor  )						->					np.ndarray:
           if self.framework == "tf":
               _lowercase							= tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
           elif self.framework == "pt":
               _lowercase							= torch.nonzero(input_ids == self.tokenizer.mask_token_id						,as_tuple=__A  )
           else:
               raise ValueError('Unsupported framework'  )
           return masked_index







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	GenericTensor  )						->					np.ndarray:
           _lowercase							= self.get_masked_index(__A  )
           _lowercase							= 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    __UpperCAmelCase (    self	:	Tuple						,__A	:	GenericTensor  )						->					List[str]:
           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    __UpperCAmelCase (    self	:	Tuple						,__A	:	List[str]						,__A	:	Any=None						,**__A	:	Tuple  )						->					Dict[str, GenericTensor]:
           if return_tensors is None:
               _lowercase							= self.framework
           _lowercase							= self.tokenizer(__A						,return_tensors=__A  )
           self.ensure_exactly_one_mask_token(__A  )
           return model_inputs







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	Any  )						->					Tuple:
           _lowercase							= self.model(**__A  )
           _lowercase							= model_inputs['input_ids']
           return model_outputs







       def    __UpperCAmelCase (    self	:	Union[str, Any]						,__A	:	Tuple						,__A	:	Dict=5						,__A	:	str=None  )						->					Dict:
           # Cap top_k if there are targets
           if target_ids is not None and target_ids.shape[0] < top_k:
               _lowercase							= target_ids.shape[0]
           _lowercase							= model_outputs['input_ids'][0]
           _lowercase							= model_outputs['logits']

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

               _lowercase							= outputs.numpy()

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

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

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

               _lowercase						,		_lowercase							= probs.topk(__A  )

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

                   _lowercase							= p
                   # Filter padding out:
                   _lowercase							= 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
                   _lowercase							= self.tokenizer.decode(__A						,skip_special_tokens=__A  )
                   _lowercase							= {'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    __UpperCAmelCase (    self	:	Tuple						,__A	:	Tuple						,__A	:	List[str]=None  )						->					List[Any]:
           if isinstance(__A						,__A  ):
               _lowercase							= [targets]
           try:
               _lowercase							= self.tokenizer.get_vocab()
           except Exception:
               _lowercase							= {}
           _lowercase							= []
           for target in targets:
               _lowercase							= vocab.get(__A						,__A  )
               if id_ is None:
                   _lowercase							= 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
                   _lowercase							= 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_  )
           _lowercase							= list(set(__A  )  )
           if len(__A  ) == 0:
               raise ValueError('At least one target must be provided when passed.'  )
           _lowercase							= np.array(__A  )
           return target_ids







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	str=None						,__A	:	Any=None  )						->					Tuple:
           _lowercase							= {}

           if targets is not None:
               _lowercase							= self.get_target_ids(__A						,__A  )
               _lowercase							= target_ids

           if top_k is not None:
               _lowercase							= 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	:	Tuple						,**__A	:	int  )						->					Optional[Any]:
           _lowercase							= super().__call__(__A						,**__A  )
           if isinstance(__A						,__A  ) and len(__A  ) == 1:
               return outputs[0]
           return outputs






import string

import numpy

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :int			,							snake_case__  :int     )      ->						int:
  return b if a == 0 else greatest_common_divisor(b % a			,							snake_case__     )





class 				A_				:







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Dict      =  string.ascii_uppercase + string.digits
       # This cipher takes alphanumerics into account
       # i.e. a total of 36 characters

       # take x and return x % len(key_string)
       SCREAMING_SNAKE_CASE_      : Dict      =  numpy.vectorize(lambda UpperCAmelCase	: x % 3_6	)

       SCREAMING_SNAKE_CASE_      : List[Any]      =  numpy.vectorize(UpperCAmelCase	)







       def __init__(    self	:	Optional[Any]						,__A	:	numpy.ndarray  )						->					None:
         _lowercase							= self.modulus(__A  )  # mod36 calc's on the encrypt key
         self.check_determinant()  # validate the determinant of the encryption key
         _lowercase							= encrypt_key.shape[0]







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	str  )						->					int:
         return self.key_string.index(__A  )







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	int  )						->					str:
         return self.key_string[round(__A  )]







       def    __UpperCAmelCase (    self	:	str  )						->					None:
         _lowercase							= round(numpy.linalg.det(self.encrypt_key  )  )

         if det < 0:
           _lowercase							= det % len(self.key_string  )

         _lowercase							= len(self.key_string  )
         if greatest_common_divisor(__A						,len(self.key_string  )  ) != 1:
           _lowercase							= (
               F"""determinant modular {req_l} of encryption key({det}) """
               F"""is not co prime w.r.t {req_l}.\nTry another key."""
           )
           raise ValueError(__A  )







       def    __UpperCAmelCase (    self	:	Any						,__A	:	str  )						->					str:
         _lowercase							= [char for char in text.upper() if char in self.key_string]

         _lowercase							= chars[-1]
         while len(__A  ) % self.break_key != 0:
           chars.append(__A  )

         return "".join(__A  )







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	str  )						->					str:
         _lowercase							= self.process_text(text.upper()  )
         _lowercase							= ''

         for i in range(0						,len(__A  ) - self.break_key + 1						,self.break_key  ):
           _lowercase							= text[i : i + self.break_key]
           _lowercase							= [self.replace_letters(__A  ) for char in batch]
           _lowercase							= numpy.array([vec]  ).T
           _lowercase							= self.modulus(self.encrypt_key.dot(__A  )  ).T.tolist()[
               0
           ]
           _lowercase							= ''.join(
               self.replace_digits(__A  ) for num in batch_encrypted  )
           encrypted += encrypted_batch

         return encrypted







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					numpy.ndarray:
         _lowercase							= round(numpy.linalg.det(self.encrypt_key  )  )

         if det < 0:
           _lowercase							= det % len(self.key_string  )
         _lowercase							= None
         for i in range(len(self.key_string  )  ):
           if (det * i) % len(self.key_string  ) == 1:
             _lowercase							= i
             break

         _lowercase							= (
             det_inv
             * numpy.linalg.det(self.encrypt_key  )
             * numpy.linalg.inv(self.encrypt_key  )
         )

         return self.to_int(self.modulus(__A  )  )







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	str  )						->					str:
         _lowercase							= self.make_decrypt_key()
         _lowercase							= self.process_text(text.upper()  )
         _lowercase							= ''

         for i in range(0						,len(__A  ) - self.break_key + 1						,self.break_key  ):
           _lowercase							= text[i : i + self.break_key]
           _lowercase							= [self.replace_letters(__A  ) for char in batch]
           _lowercase							= numpy.array([vec]  ).T
           _lowercase							= self.modulus(decrypt_key.dot(__A  )  ).T.tolist()[0]
           _lowercase							= ''.join(
               self.replace_digits(__A  ) for num in batch_decrypted  )
           decrypted += decrypted_batch

         return decrypted

def 							SCREAMING_SNAKE_CASE__       (  )      ->						None:
  _lowercase							= int(input('Enter the order of the encryption key: '     )     )
  _lowercase							= []

  print('Enter each row of the encryption key with space separated integers'     )
  for _ in range(snake_case__     ):
    _lowercase							= [int(snake_case__     ) for x in input().split()]
    hill_matrix.append(snake_case__     )

  _lowercase							= HillCipher(numpy.array(snake_case__     )     )

  print('Would you like to encrypt or decrypt some text? (1 or 2)'     )
  _lowercase							= input('\n1. Encrypt\n2. Decrypt\n'     )
  if option == "1":
    _lowercase							= input('What text would you like to encrypt?: '     )
    print('Your encrypted text is:'     )
    print(hc.encrypt(snake_case__     )     )
  elif option == "2":
    _lowercase							= input('What text would you like to decrypt?: '     )
    print('Your decrypted text is:'     )
    print(hc.decrypt(snake_case__     )     )


if __name__ == "__main__":
      import doctest

      doctest.testmod()

      main()