
"""simple docstring"""

import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


UpperCamelCase			:       Tuple									=				logging.getLogger(__name__)

@dataclass(frozen=__SCREAMING_SNAKE_CASE    )
class __lowerCAmelCase	:
     lowercase		     =		42
     lowercase		     =		42
     lowercase		     =		None
     lowercase		     =		None
     lowercase		     =		None


@dataclass(frozen=__SCREAMING_SNAKE_CASE    )
class __lowerCAmelCase	:
     lowercase		     =		42
     lowercase		     =		None
     lowercase		     =		None
     lowercase		     =		None
     lowercase		     =		None


if is_torch_available():
      import torch
      from torch.utils.data import Dataset

      class __lowerCAmelCase	(   __SCREAMING_SNAKE_CASE    ):
           lowercase		     =		42





           def __init__(			self			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase = None			,  __UpperCAmelCase=False			,  __UpperCAmelCase = False			,  ):

            '''simple docstring'''




            __UpperCamelCase       						= hans_processors[task]()

            __UpperCamelCase       						= os.path.join(
                __UpperCAmelCase			,  'cached_{}_{}_{}_{}'.format(
                    'dev' if evaluate else 'train'			,  tokenizer.__class__.__name__			,  str(__UpperCAmelCase   )			,  __UpperCAmelCase			,  )			,  )
            __UpperCamelCase       						= processor.get_labels()
            if tokenizer.__class__ in (
                RobertaTokenizer,
                RobertaTokenizerFast,
                XLMRobertaTokenizer,
                BartTokenizer,
                BartTokenizerFast,
            ):
             # HACK(label indices are swapped in RoBERTa pretrained model)
             __UpperCamelCase						,			__UpperCamelCase       						= label_list[2], label_list[1]
            __UpperCamelCase       						= label_list

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            __UpperCamelCase       						= cached_features_file + '.lock'
            with FileLock(__UpperCAmelCase   ):
             if os.path.exists(__UpperCAmelCase   ) and not overwrite_cache:
              logger.info(F'Loading features from cached file {cached_features_file}'   )
              __UpperCamelCase       						= torch.load(__UpperCAmelCase   )
             else:
              logger.info(F'Creating features from dataset file at {data_dir}'   )

              __UpperCamelCase       						= (
                  processor.get_dev_examples(__UpperCAmelCase   ) if evaluate else processor.get_train_examples(__UpperCAmelCase   )
              )

              logger.info('Training examples: %s'			,  len(__UpperCAmelCase   )   )
              __UpperCamelCase       						= hans_convert_examples_to_features(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase   )
              logger.info('Saving features into cached file %s'			,  __UpperCAmelCase   )
              torch.save(self.features			,  __UpperCAmelCase   )





           def __len__(			self   ):

            '''simple docstring'''




            return len(self.features   )





           def __getitem__(			self			,  __UpperCAmelCase   ):

            '''simple docstring'''




            return self.features[i]







           def 		UpperCAmelCase      (			self   ):

            '''simple docstring'''




            return self.label_list


if is_tf_available():
      import tensorflow as tf

      class __lowerCAmelCase	:
           lowercase		     =		42





           def __init__(			self			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase = 128			,  __UpperCAmelCase=False			,  __UpperCAmelCase = False			,  ):

            '''simple docstring'''




            __UpperCamelCase       						= hans_processors[task]()
            __UpperCamelCase       						= processor.get_labels()
            if tokenizer.__class__ in (
                RobertaTokenizer,
                RobertaTokenizerFast,
                XLMRobertaTokenizer,
                BartTokenizer,
                BartTokenizerFast,
            ):
             # HACK(label indices are swapped in RoBERTa pretrained model)
             __UpperCamelCase						,			__UpperCamelCase       						= label_list[2], label_list[1]
            __UpperCamelCase       						= label_list

            __UpperCamelCase       						= processor.get_dev_examples(__UpperCAmelCase   ) if evaluate else processor.get_train_examples(__UpperCAmelCase   )
            __UpperCamelCase       						= hans_convert_examples_to_features(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase   )

            def gen():
             for ex_index, ex in tqdm.tqdm(enumerate(self.features   )			,  desc='convert examples to features'   ):
              if ex_index % 1_0000 == 0:
               logger.info('Writing example %d of %d' % (ex_index, len(__UpperCAmelCase   ))   )

              yield (
                  {
                      "example_id": 0,
                      "input_ids": ex.input_ids,
                      "attention_mask": ex.attention_mask,
                      "token_type_ids": ex.token_type_ids,
                  },
                  ex.label,
              )

            __UpperCamelCase       						= tf.data.Dataset.from_generator(
                __UpperCAmelCase			,  (
                    {
                        'example_id': tf.intaa,
                        'input_ids': tf.intaa,
                        'attention_mask': tf.intaa,
                        'token_type_ids': tf.intaa,
                    },
                    tf.intaa,
                )			,  (
                    {
                        'example_id': tf.TensorShape([]   ),
                        'input_ids': tf.TensorShape([None, None]   ),
                        'attention_mask': tf.TensorShape([None, None]   ),
                        'token_type_ids': tf.TensorShape([None, None]   ),
                    },
                    tf.TensorShape([]   ),
                )			,  )





           def 		UpperCAmelCase      (			self   ):

            '''simple docstring'''




            return self.dataset





           def __len__(			self   ):

            '''simple docstring'''




            return len(self.features   )





           def __getitem__(			self			,  __UpperCAmelCase   ):

            '''simple docstring'''




            return self.features[i]







           def 		UpperCAmelCase      (			self   ):

            '''simple docstring'''




            return self.label_list

class __lowerCAmelCase	(   __SCREAMING_SNAKE_CASE    ):





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self._create_examples(self._read_tsv(os.path.join(__UpperCAmelCase			,  'heuristics_train_set.txt'   )   )			,  'train'   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self._create_examples(self._read_tsv(os.path.join(__UpperCAmelCase			,  'heuristics_evaluation_set.txt'   )   )			,  'dev'   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      return ["contradiction", "entailment", "neutral"]







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= []
      for i, line in enumerate(__UpperCAmelCase   ):
       if i == 0:
        continue
       __UpperCamelCase       						= '%s-%s' % (set_type, line[0])
       __UpperCamelCase       						= line[5]
       __UpperCamelCase       						= line[6]
       __UpperCamelCase       						= line[7][2:] if line[7].startswith('ex'   ) else line[7]
       __UpperCamelCase       						= line[0]
       examples.append(InputExample(guid=__UpperCAmelCase			,  text_a=__UpperCAmelCase			,  text_b=__UpperCAmelCase			,  label=__UpperCAmelCase			,  pairID=__UpperCAmelCase   )   )
      return examples






def 							A		(       snake_case   :List[InputExample]       ,      snake_case   :List[str]       ,      snake_case   :int       ,      snake_case   :PreTrainedTokenizer       ,      )   ->			Optional[int]:
 __UpperCamelCase       						= {label: i for i, label in enumerate(snake_case	)}

 __UpperCamelCase       						= []
 for ex_index, example in tqdm.tqdm(enumerate(snake_case	)       ,      desc='convert examples to features'	):
  if ex_index % 1_0_0_0_0 == 0:
   logger.info('Writing example %d' % (ex_index)	)

  __UpperCamelCase       						= tokenizer(
      example.text_a       ,      example.text_b       ,      add_special_tokens=snake_case       ,      max_length=snake_case       ,      padding='max_length'       ,      truncation=snake_case       ,      return_overflowing_tokens=snake_case       ,      )

  __UpperCamelCase       						= label_map[example.label] if example.label in label_map else 0

  __UpperCamelCase       						= int(example.pairID	)

  features.append(InputFeatures(**snake_case       ,      label=snake_case       ,      pairID=snake_case	)	)

 for i, example in enumerate(examples[:5]	):
  logger.info('*** Example ***'	)
  logger.info(f'guid: {example}'	)
  logger.info(f'features: {features[i]}'	)

 return features


UpperCamelCase			:       int									=				{
    "hans": 3,
}





UpperCamelCase			:       Any									=				{
    "hans": HansProcessor,
}





"""simple docstring"""

import string

import numpy






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

class __lowerCAmelCase	:
     lowercase		     =		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)
     lowercase		     =		numpy.vectorize(lambda __SCREAMING_SNAKE_CASE    : x % 36    )

     lowercase		     =		numpy.vectorize(__SCREAMING_SNAKE_CASE    )





     def __init__(			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.modulus(__UpperCAmelCase   )  # mod36 calc's on the encrypt key
      self.check_determinant()  # validate the determinant of the encryption key
      __UpperCamelCase       						= encrypt_key.shape[0]





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string.index(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string[round(__UpperCAmelCase   )]





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= round(numpy.linalg.det(self.encrypt_key   )   )

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

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





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= [char for char in text.upper() if char in self.key_string]

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

      return "".join(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.process_text(text.upper()   )
      __UpperCamelCase       						= ''

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

      return encrypted





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= round(numpy.linalg.det(self.encrypt_key   )   )

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

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

      return self.to_int(self.modulus(__UpperCAmelCase   )   )







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.make_decrypt_key()
      __UpperCamelCase       						= self.process_text(text.upper()   )
      __UpperCamelCase       						= ''

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

      return decrypted






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

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

 __UpperCamelCase       						= HillCipher(numpy.array(snake_case	)	)

 print('Would you like to encrypt or decrypt some text? (1 or 2)'	)
 __UpperCamelCase       						= input('\n1. Encrypt\n2. Decrypt\n'	)
 if option == "1":
  __UpperCamelCase       						= input('What text would you like to encrypt?: '	)
  print('Your encrypted text is:'	)
  print(hc.encrypt(snake_case	)	)
 elif option == "2":
  __UpperCamelCase       						= 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()



