



import string

import numpy





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase    ):
    return b if a == 0 else greatest_common_divisor(b % a       ,			__lowerCamelCase    )

class    _A	:
       UpperCamelCase__  :   Tuple						 =						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)
       UpperCamelCase__  :   Optional[Any]						 =						numpy.vectorize(lambda __UpperCAmelCase   : x % 36   )

       UpperCamelCase__  :   Union[str, Any]						 =						numpy.vectorize(A_   )



       def __init__(		self							:					Union[str, Any]					,		__SCREAMING_SNAKE_CASE							:					numpy.ndarray):


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					str):


           '''simple docstring'''

           return self.key_string.index(snake_case__)



       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					int):


           '''simple docstring'''

           return self.key_string[round(snake_case__)]



       def 		_lowerCamelCase      (		self							:					Optional[int]):


           '''simple docstring'''

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

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

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



       def 		_lowerCamelCase      (		self							:					Union[str, Any]					,		__SCREAMING_SNAKE_CASE							:					str):


           '''simple docstring'''

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

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

           return "".join(snake_case__)



       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					str):


           '''simple docstring'''

           __a							=    self.process_text(text.upper())
           __a							=    ""

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

           return encrypted



       def 		_lowerCamelCase      (		self							:					List[Any]):


           '''simple docstring'''

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

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

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

           return self.to_int(self.modulus(snake_case__))





       def 		_lowerCamelCase      (		self							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					str):


           '''simple docstring'''

           __a							=    self.make_decrypt_key()
           __a							=    self.process_text(text.upper())
           __a							=    ""

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

           return decrypted





def 					__snake_case     (      ):
    __a							=    int(input('''Enter the order of the encryption key: '''    )    )
    __a							=    []

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

    __a							=    HillCipher(numpy.array(__lowerCamelCase    )    )

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


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 main()






from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
 import torch

 from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

__snake_case						:Dict						=					logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase   ):



       def __init__(		self							:					int					,		*__SCREAMING_SNAKE_CASE							:					Optional[int]					,		**__SCREAMING_SNAKE_CASE							:					str):


           '''simple docstring'''

           super().__init__(*__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           requires_backends(self					,		'''vision''')
           self.check_model_type(
               TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING)



       def 		_lowerCamelCase      (		self							:					int					,		__SCREAMING_SNAKE_CASE							:					int=None					,		__SCREAMING_SNAKE_CASE							:					int=None					,		__SCREAMING_SNAKE_CASE							:					Tuple=None):


           '''simple docstring'''

           __a							=    {}
           __a							=    {}

           if prompt is not None:
               __a							=    prompt

           if generate_kwargs is not None:
               __a							=    generate_kwargs
           if max_new_tokens is not None:
               if "generate_kwargs" not in forward_kwargs:
                   __a							=    {}
               if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
                   raise ValueError(
                       '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'''
                       ''' please use only one''')
               __a							=    max_new_tokens
           return preprocess_params, forward_kwargs, {}



       def __call__(		self							:					Any					,		__SCREAMING_SNAKE_CASE							:					Union[str, List[str], "Image.Image", List["Image.Image"]]					,		**__SCREAMING_SNAKE_CASE							:					Any):


           '''simple docstring'''

           return super().__call__(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Dict					,		__SCREAMING_SNAKE_CASE							:					Optional[Any]=None):


           '''simple docstring'''

           __a							=    load_image(__SCREAMING_SNAKE_CASE)

           if prompt is not None:
               if not isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE):
                   raise ValueError(
                       F'Received an invalid text input, got - {type(__SCREAMING_SNAKE_CASE)} - but expected a single string. '
                       '''Note also that one single text can be provided for conditional image to text generation.''')

               __a							=    self.model.config.model_type

               if model_type == "git":
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   __a							=    self.tokenizer(text=__SCREAMING_SNAKE_CASE					,		add_special_tokens=__SCREAMING_SNAKE_CASE).input_ids
                   __a							=    [self.tokenizer.cls_token_id] + input_ids
                   __a							=    torch.tensor(__SCREAMING_SNAKE_CASE).unsqueeze(0)
                   model_inputs.update({'''input_ids''': input_ids})

               elif model_type == "pix2struct":
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		header_text=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)

               elif model_type != "vision-encoder-decoder":
                   # vision-encoder-decoder does not support conditional generation
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   __a							=    self.tokenizer(__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   model_inputs.update(__SCREAMING_SNAKE_CASE)

               else:
                   raise ValueError(F'Model type {model_type} does not support conditional text generation')

           else:
               __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)

           if self.model.config.model_type == "git" and prompt is None:
               __a							=    None

           return model_inputs



       def 		_lowerCamelCase      (		self							:					List[Any]					,		__SCREAMING_SNAKE_CASE							:					str					,		__SCREAMING_SNAKE_CASE							:					Tuple=None):


           '''simple docstring'''

           if (
               "input_ids" in model_inputs
               and isinstance(model_inputs['''input_ids''']					,		__SCREAMING_SNAKE_CASE)
               and all(x is None for x in model_inputs['''input_ids'''])
           ):
               __a							=    None

           if generate_kwargs is None:
               __a							=    {}
           # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
           #  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
           #  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
           #  in the `_prepare_model_inputs` method.
           __a							=    model_inputs.pop(self.model.main_input_name)
           __a							=    self.model.generate(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           return model_outputs





       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					Union[str, Any]):


           '''simple docstring'''

           __a							=    []
           for output_ids in model_outputs:
               __a							=    {
                   '''generated_text''': self.tokenizer.decode(
                       __SCREAMING_SNAKE_CASE					,		skip_special_tokens=__SCREAMING_SNAKE_CASE					,		)
               }
               records.append(__SCREAMING_SNAKE_CASE)
           return records





