'''simple docstring'''

import string

import numpy
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 return b if a == 0 else greatest_common_divisor(b % a		,					UpperCAmelCase					)



class       UpperCAmelCase  :





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   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 		=   numpy.vectorize(lambda a__ : x % 3_6 )

       SCREAMING_SNAKE_CASE 		=   numpy.vectorize(a__ )

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

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  int:
        return self.key_string.index(__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        return self.key_string[round(__lowerCAmelCase			)]

       def _lowerCAmelCase(						self			)  ->  None:
        lowercase__    :   int						= round(numpy.linalg.det(self.encrypt_key			)			)

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

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

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Tuple						= [char for char in text.upper() if char in self.key_string]

        lowercase__    :   Optional[Any]						= chars[-1]
        while len(__lowerCAmelCase			) % self.break_key != 0:
         chars.append(__lowerCAmelCase			)

        return "".join(__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   Optional[int]						= self.process_text(text.upper()			)
        lowercase__    :   List[Any]						= ''''''

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

        return encrypted

       def _lowerCAmelCase(						self			)  ->  numpy.ndarray:
        lowercase__    :   Optional[int]						= round(numpy.linalg.det(self.encrypt_key			)			)

        if det < 0:
         lowercase__    :   Dict						= det % len(self.key_string			)
        lowercase__    :   List[str]						= None
        for i in range(len(self.key_string			)			):
         if (det * i) % len(self.key_string			) == 1:
          lowercase__    :   Tuple						= i
          break

        lowercase__    :   Optional[int]						= (
            det_inv
            * numpy.linalg.det(self.encrypt_key			)
            * numpy.linalg.inv(self.encrypt_key			)
        )

        return self.to_int(self.modulus(__lowerCAmelCase			)			)


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   List[Any]						= self.make_decrypt_key()
        lowercase__    :   Optional[int]						= self.process_text(text.upper()			)
        lowercase__    :   str						= ''''''

        for i in range(0     ,       len(__lowerCAmelCase			) - self.break_key + 1     ,       self.break_key			):
         lowercase__    :   Optional[int]						= text[i : i + self.break_key]
         lowercase__    :   List[Any]						= [self.replace_letters(__lowerCAmelCase			) for char in batch]
         lowercase__    :   str						= numpy.array([vec]			).T
         lowercase__    :   str						= self.modulus(decrypt_key.dot(__lowerCAmelCase			)			).T.tolist()[0]
         lowercase__    :   Union[str, Any]						= ''''''.join(
             self.replace_digits(__lowerCAmelCase			) for num in batch_decrypted			)
         decrypted += decrypted_batch

        return decrypted


def       __UpperCamelCase	(       ):
 lowercase__    :   Optional[Any]						= int(input('''Enter the order of the encryption key: '''					)					)
 lowercase__    :   str						= []

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

 lowercase__    :   Dict						= HillCipher(numpy.array(UpperCAmelCase					)					)

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


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  main()


'''simple docstring'''

from collections import UserDict
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_torch_available():
  from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
  from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
  from ..tf_utils import stable_softmax

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



@add_end_docstrings(a__ )
class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       **__lowerCAmelCase			)  ->  int:
        super().__init__(**__lowerCAmelCase			)

        requires_backends(self     ,       '''vision'''			)
        self.check_model_type(
            TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
            if self.framework == '''tf'''
            else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING			)

       def __call__(						self     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)  ->  List[str]:
        return super().__call__(__lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        lowercase__    :   str						= {}
        if "candidate_labels" in kwargs:
         lowercase__    :   str						= kwargs['''candidate_labels''']
        if "hypothesis_template" in kwargs:
         lowercase__    :   str						= kwargs['''hypothesis_template''']

        return preprocess_params, {}, {}

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None     ,       __lowerCAmelCase="This is a photo of {}."			)  ->  Any:
        lowercase__    :   Union[str, Any]						= load_image(__lowerCAmelCase			)
        lowercase__    :   List[str]						= self.image_processor(images=[image]     ,       return_tensors=self.framework			)
        lowercase__    :   Union[str, Any]						= candidate_labels
        lowercase__    :   int						= [hypothesis_template.format(__lowerCAmelCase			) for x in candidate_labels]
        lowercase__    :   Any						= self.tokenizer(__lowerCAmelCase     ,       return_tensors=self.framework     ,       padding=__lowerCAmelCase			)
        lowercase__    :   Any						= [text_inputs]
        return inputs

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        lowercase__    :   Any						= model_inputs.pop('''candidate_labels'''			)
        lowercase__    :   int						= model_inputs.pop('''text_inputs'''			)
        if isinstance(text_inputs[0]     ,       __lowerCAmelCase			):
         lowercase__    :   Union[str, Any]						= text_inputs[0]
        else:
         # Batching case.
         lowercase__    :   Optional[Any]						= text_inputs[0][0]

        lowercase__    :   Any						= self.model(**__lowerCAmelCase     ,       **__lowerCAmelCase			)

        lowercase__    :   Any						= {
            '''candidate_labels''': candidate_labels,
            '''logits''': outputs.logits_per_image,
        }
        return model_outputs


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  List[str]:
        lowercase__    :   Union[str, Any]						= model_outputs.pop('''candidate_labels'''			)
        lowercase__    :   Optional[int]						= model_outputs['''logits'''][0]
        if self.framework == "pt":
         lowercase__    :   Optional[int]						= logits.softmax(dim=-1			).squeeze(-1			)
         lowercase__    :   Any						= probs.tolist()
         if not isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   Dict						= [scores]
        elif self.framework == "tf":
         lowercase__    :   List[Any]						= stable_softmax(__lowerCAmelCase     ,       axis=-1			)
         lowercase__    :   str						= probs.numpy().tolist()
        else:
         raise ValueError(F"""Unsupported framework: {self.framework}"""			)

        lowercase__    :   Optional[int]						= [
            {'''score''': score, '''label''': candidate_label}
            for score, candidate_label in sorted(zip(__lowerCAmelCase     ,       __lowerCAmelCase			)     ,       key=lambda __lowerCAmelCase			: -x[0]			)
        ]
        return result

