
"""simple docstring"""



import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812






def 	__snake_case  (    ):






       """simple docstring"""



       print('Making key files...'						)
       make_key_files('rsa'     ,  1024						)
       print('Key files generation successful.'						)






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Dict						):






       """simple docstring"""



       print('Generating prime p...'						)
       _lowerCAmelCase  	=			rabinMiller.generate_large_prime(lowerCAmelCase__						)
       print('Generating prime q...'						)
       _lowerCAmelCase  	=			rabinMiller.generate_large_prime(lowerCAmelCase__						)
       _lowerCAmelCase  	=			p * q

       print('Generating e that is relatively prime to (p - 1) * (q - 1)...'						)
       while True:
              _lowerCAmelCase  	=			random.randrange(2 ** (key_size - 1)     ,  2 ** (key_size)						)
              if cryptoMath.gcd(lowerCAmelCase__     ,  (p - 1) * (q - 1)						) == 1:
                     break

       print('Calculating d that is mod inverse of e...'						)
       _lowerCAmelCase  	=			cryptoMath.find_mod_inverse(lowerCAmelCase__     ,  (p - 1) * (q - 1)						)

       _lowerCAmelCase  	=			(n, e)
       _lowerCAmelCase  	=			(n, d)
       return (public_key, private_key)






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Tuple     ,  SCREAMING_SNAKE_CASE:					List[str]						):






       """simple docstring"""



       if os.path.exists(f"""{name}_pubkey.txt"""						) or os.path.exists(f"""{name}_privkey.txt"""						):
              print('\nWARNING:'						)
              print(
                  f"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
                  'Use a different name or delete these files and re-run this program.'						)
              sys.exit()

       _lowerCAmelCase	,		_lowerCAmelCase  	=			generate_key(lowerCAmelCase__						)
       print(f"""\nWriting public key to file {name}_pubkey.txt..."""						)
       with open(f"""{name}_pubkey.txt"""     ,  'w'						) as out_file:
              out_file.write(f"""{key_size},{public_key[0]},{public_key[1]}"""						)

       print(f"""Writing private key to file {name}_privkey.txt..."""						)
       with open(f"""{name}_privkey.txt"""     ,  'w'						) as out_file:
              out_file.write(f"""{key_size},{private_key[0]},{private_key[1]}"""						)


if __name__ == "__main__":
 main()








"""simple docstring"""



import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf

	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

_snake_case          =						logging.get_logger(__name__)
class        _SCREAMING_SNAKE_CASE  (  enum.Enum							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Any							=					0
				SCREAMING_SNAKE_CASE_:							str							=					1






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							int							=					"generated"


				def __init__(					self	:			Optional[Any]				,     *UpperCAmelCase_	:			Dict				,     **UpperCAmelCase_	:			Union[str, Any]  )		->  Optional[Any]:







											"""simple docstring"""




											super().__init__(*UpperCAmelCase_				,     **UpperCAmelCase_  )

											self.check_model_type(
											    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
											    if self.framework == 'tf'
											    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING  )


				def 				__lowerCamelCase	(					self	:			List[str]				,     UpperCAmelCase_	:			Any=None				,     UpperCAmelCase_	:			List[str]=None				,     UpperCAmelCase_	:			Union[str, Any]=None				,     UpperCAmelCase_	:			List[str]=None				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Optional[Any]=None				,     **UpperCAmelCase_	:			Union[str, Any]				,     )		->  int:







											"""simple docstring"""




											_lowerCAmelCase  	=			{}
											if truncation is not None:
																		_lowerCAmelCase  	=			truncation

											_lowerCAmelCase  	=			generate_kwargs

											_lowerCAmelCase  	=			{}
											if return_tensors is not None and return_type is None:
																		_lowerCAmelCase  	=			ReturnType.TENSORS if return_tensors else ReturnType.TEXT
											if return_type is not None:
																		_lowerCAmelCase  	=			return_type

											if clean_up_tokenization_spaces is not None:
																		_lowerCAmelCase  	=			clean_up_tokenization_spaces

											if stop_sequence is not None:
																		_lowerCAmelCase  	=			self.tokenizer.encode(UpperCAmelCase_				,     add_special_tokens=UpperCAmelCase_  )
																		if len(UpperCAmelCase_  ) > 1:
																									warnings.warn(
																									    'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
																									    ' the stop sequence will be used as the stop sequence string in the interim.'  )
																		_lowerCAmelCase  	=			stop_sequence_ids[0]

											return preprocess_params, forward_params, postprocess_params


				def 				__lowerCamelCase	(					self	:			List[Any]				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  Optional[Any]:







											"""simple docstring"""




											return True


				def 				__lowerCamelCase	(					self	:			Union[str, Any]				,     *UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			int  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.model.config.prefix if self.model.config.prefix is not None else ''
											if isinstance(args[0]				,     UpperCAmelCase_  ):
																		if self.tokenizer.pad_token_id is None:
																									raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input'  )
																		_lowerCAmelCase  	=			([prefix + arg for arg in args[0]],)
																		_lowerCAmelCase  	=			True

											elif isinstance(args[0]				,     UpperCAmelCase_  ):
																		_lowerCAmelCase  	=			(prefix + args[0],)
																		_lowerCAmelCase  	=			False
											else:
																		raise ValueError(
																		    F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`"""  )
											_lowerCAmelCase  	=			self.tokenizer(*UpperCAmelCase_				,     padding=UpperCAmelCase_				,     truncation=UpperCAmelCase_				,     return_tensors=self.framework  )
											# This is produced by tokenizers but is an invalid generate kwargs
											if "token_type_ids" in inputs:
																		del inputs["token_type_ids"]
											return inputs


				def __call__(					self	:			Union[str, Any]				,     *UpperCAmelCase_	:			Optional[Any]				,     **UpperCAmelCase_	:			Tuple  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			super().__call__(*UpperCAmelCase_				,     **UpperCAmelCase_  )
											if (
											    isinstance(args[0]				,     UpperCAmelCase_  )
											    and all(isinstance(UpperCAmelCase_				,     UpperCAmelCase_  ) for el in args[0]  )
											    and all(len(UpperCAmelCase_  ) == 1 for res in result  )
											):
																		return [res[0] for res in result]
											return result


				def 				__lowerCamelCase	(					self	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			Dict=TruncationStrategy.DO_NOT_TRUNCATE				,     **UpperCAmelCase_	:			Tuple  )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			self._parse_and_tokenize(UpperCAmelCase_				,     truncation=UpperCAmelCase_				,     **UpperCAmelCase_  )
											return inputs


				def 				__lowerCamelCase	(					self	:			Optional[Any]				,     UpperCAmelCase_	:			List[Any]				,     **UpperCAmelCase_	:			List[str]  )		->  Any:







											"""simple docstring"""




											if self.framework == "pt":
																		_lowerCAmelCase	,		_lowerCAmelCase  	=			model_inputs['input_ids'].shape
											elif self.framework == "tf":
																		_lowerCAmelCase	,		_lowerCAmelCase  	=			tf.shape(model_inputs['input_ids']  ).numpy()

											_lowerCAmelCase  	=			generate_kwargs.get('min_length'				,     self.model.config.min_length  )
											_lowerCAmelCase  	=			generate_kwargs.get('max_length'				,     self.model.config.max_length  )
											self.check_inputs(UpperCAmelCase_				,     generate_kwargs['min_length']				,     generate_kwargs['max_length']  )
											_lowerCAmelCase  	=			self.model.generate(**UpperCAmelCase_				,     **UpperCAmelCase_  )
											_lowerCAmelCase  	=			output_ids.shape[0]
											if self.framework == "pt":
																		_lowerCAmelCase  	=			output_ids.reshape(UpperCAmelCase_				,     out_b // in_b				,     *output_ids.shape[1:]  )
											elif self.framework == "tf":
																		_lowerCAmelCase  	=			tf.reshape(UpperCAmelCase_				,     (in_b, out_b // in_b, *output_ids.shape[1:])  )
											return {"output_ids": output_ids}







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			Tuple				,     UpperCAmelCase_	:			Union[str, Any]=ReturnType.TEXT				,     UpperCAmelCase_	:			Optional[Any]=False  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			[]
											for output_ids in model_outputs["output_ids"][0]:
																		if return_type == ReturnType.TENSORS:
																									_lowerCAmelCase  	=			{F"""{self.return_name}_token_ids""": output_ids}
																		elif return_type == ReturnType.TEXT:
																									_lowerCAmelCase  	=			{
																									    F"""{self.return_name}_text""": self.tokenizer.decode(
																									        UpperCAmelCase_				,     skip_special_tokens=UpperCAmelCase_				,     clean_up_tokenization_spaces=UpperCAmelCase_				,     )
																									}
																		records.append(UpperCAmelCase_  )
											return records






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Optional[Any]							=					"summary"


				def __call__(					self	:			Optional[int]				,     *UpperCAmelCase_	:			Optional[Any]				,     **UpperCAmelCase_	:			Dict  )		->  int:







											"""simple docstring"""




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







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  bool:







											"""simple docstring"""




											if max_length < min_length:
																		logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}."""  )

											if input_length < max_length:
																		logger.warning(
																		    F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """
																		    'a summarization task, where outputs shorter than the input are typically wanted, you might '
																		    F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})"""  )






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Optional[int]							=					"translation"


				def 				__lowerCamelCase	(					self	:			str				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  Any:







											"""simple docstring"""




											if input_length > 0.9 * max_length:
																		logger.warning(
																		    F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """
																		    'increasing your max_length manually, e.g. translator(\'...\', max_length=400)'  )
											return True


				def 				__lowerCamelCase	(					self	:			Optional[Any]				,     *UpperCAmelCase_	:			List[Any]				,     UpperCAmelCase_	:			Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Dict=None  )		->  Optional[int]:







											"""simple docstring"""




											if getattr(self.tokenizer				,     '_build_translation_inputs'				,     UpperCAmelCase_  ):
																		return self.tokenizer._build_translation_inputs(
																		    *UpperCAmelCase_				,     return_tensors=self.framework				,     truncation=UpperCAmelCase_				,     src_lang=UpperCAmelCase_				,     tgt_lang=UpperCAmelCase_  )
											else:
																		return super()._parse_and_tokenize(*UpperCAmelCase_				,     truncation=UpperCAmelCase_  )


				def 				__lowerCamelCase	(					self	:			Union[str, Any]				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Union[str, Any]=None				,     **UpperCAmelCase_	:			Optional[int]  )		->  Union[str, Any]:







											"""simple docstring"""




											_lowerCAmelCase	,		_lowerCAmelCase	,		_lowerCAmelCase  	=			super()._sanitize_parameters(**UpperCAmelCase_  )
											if src_lang is not None:
																		_lowerCAmelCase  	=			src_lang
											if tgt_lang is not None:
																		_lowerCAmelCase  	=			tgt_lang
											if src_lang is None and tgt_lang is None:
																		# Backward compatibility, direct arguments use is preferred.
																		_lowerCAmelCase  	=			kwargs.get('task'				,     self.task  )
																		_lowerCAmelCase  	=			task.split('_'  )
																		if task and len(UpperCAmelCase_  ) == 4:
																									# translation, XX, to YY
																									_lowerCAmelCase  	=			items[1]
																									_lowerCAmelCase  	=			items[3]
											return preprocess_params, forward_params, postprocess_params







				def __call__(					self	:			Optional[int]				,     *UpperCAmelCase_	:			int				,     **UpperCAmelCase_	:			Optional[int]  )		->  Union[str, Any]:







											"""simple docstring"""




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






