





"""simple docstring"""






from __future__ import annotations

__UpperCAmelCase						=			tuple[int, int, int]
__UpperCAmelCase						=			tuple[str, str, str]


# used alphabet --------------------------
# from string.ascii_uppercase
__UpperCAmelCase						=			'''ABCDEFGHIJKLMNOPQRSTUVWXYZ'''

# -------------------------- default selection --------------------------
# rotors --------------------------
__UpperCAmelCase						=			'''EGZWVONAHDCLFQMSIPJBYUKXTR'''
__UpperCAmelCase						=			'''FOBHMDKEXQNRAULPGSJVTYICZW'''
__UpperCAmelCase						=			'''ZJXESIUQLHAVRMDOYGTNFWPBKC'''
# reflector --------------------------
__UpperCAmelCase						=			{
    '''A''': '''N''',
    '''N''': '''A''',
    '''B''': '''O''',
    '''O''': '''B''',
    '''C''': '''P''',
    '''P''': '''C''',
    '''D''': '''Q''',
    '''Q''': '''D''',
    '''E''': '''R''',
    '''R''': '''E''',
    '''F''': '''S''',
    '''S''': '''F''',
    '''G''': '''T''',
    '''T''': '''G''',
    '''H''': '''U''',
    '''U''': '''H''',
    '''I''': '''V''',
    '''V''': '''I''',
    '''J''': '''W''',
    '''W''': '''J''',
    '''K''': '''X''',
    '''X''': '''K''',
    '''L''': '''Y''',
    '''Y''': '''L''',
    '''M''': '''Z''',
    '''Z''': '''M''',
}

# -------------------------- extra rotors --------------------------
__UpperCAmelCase						=			'''RMDJXFUWGISLHVTCQNKYPBEZOA'''
__UpperCAmelCase						=			'''SGLCPQWZHKXAREONTFBVIYJUDM'''
__UpperCAmelCase						=			'''HVSICLTYKQUBXDWAJZOMFGPREN'''
__UpperCAmelCase						=			'''RZWQHFMVDBKICJLNTUXAGYPSOE'''
__UpperCAmelCase						=			'''LFKIJODBEGAMQPXVUHYSTCZRWN'''
__UpperCAmelCase						=			'''KOAEGVDHXPQZMLFTYWJNBRCIUS'''






def      lowercase__ (					lowerCAmelCase__   :			RotorPositionT							,			lowerCAmelCase__   :			RotorSelectionT							,			lowerCAmelCase__   :			str			)    ->			tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:



			'''simple docstring'''
			# Checks if there are 3 unique rotors

			if (unique_rotsel := len(set(lowerCAmelCase__			)			)) < 3:
						a__  :	Dict		 =			F"Please use 3 unique rotors (not {unique_rotsel})"
						raise Exception(lowerCAmelCase__			)

			# Checks if rotor positions are valid
			a__ ,	a__ ,	a__  :	Optional[int]		 =			rotpos
			if not 0 < rotorposa <= len(lowerCAmelCase__			):
						a__  :	List[str]		 =			F"First rotor position is not within range of 1..26 ({rotorposa}"
						raise ValueError(lowerCAmelCase__			)
			if not 0 < rotorposa <= len(lowerCAmelCase__			):
						a__  :	Tuple		 =			F"Second rotor position is not within range of 1..26 ({rotorposa})"
						raise ValueError(lowerCAmelCase__			)
			if not 0 < rotorposa <= len(lowerCAmelCase__			):
						a__  :	Union[str, Any]		 =			F"Third rotor position is not within range of 1..26 ({rotorposa})"
						raise ValueError(lowerCAmelCase__			)

			# Validates string and returns dict
			a__  :	Any		 =			_plugboard(lowerCAmelCase__			)

			return rotpos, rotsel, pbdict






def      lowercase__ (					lowerCAmelCase__   :			str			)    ->			dict[str, str]:



			'''simple docstring'''

			# tests the input string if it
			# a) is type string
			# b) has even length (so pairs can be made)
			if not isinstance(lowerCAmelCase__							,			lowerCAmelCase__			):
						a__  :	Tuple		 =			F"Plugboard setting isn't type string ({type(lowerCAmelCase__			)})"
						raise TypeError(lowerCAmelCase__			)
			elif len(lowerCAmelCase__			) % 2 != 0:
						a__  :	int		 =			F"Odd number of symbols ({len(lowerCAmelCase__			)})"
						raise Exception(lowerCAmelCase__			)
			elif pbstring == "":
						return {}

			pbstring.replace(" "							,			""			)

			# Checks if all characters are unique
			a__  :	Optional[Any]		 =			set()
			for i in pbstring:
						if i not in abc:
									a__  :	Optional[Any]		 =			F"'{i}' not in list of symbols"
									raise Exception(lowerCAmelCase__			)
						elif i in tmppbl:
									a__  :	Tuple		 =			F"Duplicate symbol ({i})"
									raise Exception(lowerCAmelCase__			)
						else:
									tmppbl.add(lowerCAmelCase__			)
			del tmppbl

			# Created the dictionary
			a__  :	Dict		 =			{}
			for j in range(0							,			len(lowerCAmelCase__			) - 1							,			2			):
						a__  :	Union[str, Any]		 =			pbstring[j + 1]
						a__  :	Tuple		 =			pbstring[j]

			return pb






def      lowercase__ (					lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			RotorPositionT							,			lowerCAmelCase__   :			RotorSelectionT = (rotora, rotora, rotora)							,			lowerCAmelCase__   :			str = ""							,			)    ->			str:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			text.upper()
			a__ ,	a__ ,	a__  :	Optional[int]		 =			_validator(
			    lowerCAmelCase__							,			lowerCAmelCase__							,			plugb.upper()			)

			a__ ,	a__ ,	a__  :	List[str]		 =			rotor_position
			a__ ,	a__ ,	a__  :	str		 =			rotor_selection
			rotorposa -= 1
			rotorposa -= 1
			rotorposa -= 1

			a__  :	Union[str, Any]		 =			[]

			# encryption/decryption process --------------------------
			for symbol in text:
						if symbol in abc:
									# 1st plugboard --------------------------
									if symbol in plugboard:
												a__  :	Union[str, Any]		 =			plugboard[symbol]

									# rotor ra --------------------------
									a__  :	Any		 =			abc.index(lowerCAmelCase__			) + rotorposa
									a__  :	Tuple		 =			rotora[index % len(lowerCAmelCase__			)]

									# rotor rb --------------------------
									a__  :	List[str]		 =			abc.index(lowerCAmelCase__			) + rotorposa
									a__  :	Any		 =			rotora[index % len(lowerCAmelCase__			)]

									# rotor rc --------------------------
									a__  :	Optional[int]		 =			abc.index(lowerCAmelCase__			) + rotorposa
									a__  :	List[str]		 =			rotora[index % len(lowerCAmelCase__			)]

									# reflector --------------------------
									# this is the reason you don't need another machine to decipher

									a__  :	Optional[Any]		 =			reflector[symbol]

									# 2nd rotors
									a__  :	int		 =			abc[rotora.index(lowerCAmelCase__			) - rotorposa]
									a__  :	Dict		 =			abc[rotora.index(lowerCAmelCase__			) - rotorposa]
									a__  :	Any		 =			abc[rotora.index(lowerCAmelCase__			) - rotorposa]

									# 2nd plugboard
									if symbol in plugboard:
												a__  :	str		 =			plugboard[symbol]

									# moves/resets rotor positions
									rotorposa += 1
									if rotorposa >= len(lowerCAmelCase__			):
												a__  :	Any		 =			0
												rotorposa += 1
									if rotorposa >= len(lowerCAmelCase__			):
												a__  :	Any		 =			0
												rotorposa += 1
									if rotorposa >= len(lowerCAmelCase__			):
												a__  :	Tuple		 =			0

        # else:
        #    pass
        #    Error could be also raised
        #    raise ValueError(
        #       'Invalid symbol('+repr(symbol)+')')
						result.append(lowerCAmelCase__			)

			return "".join(lowerCAmelCase__			)


if __name__ == "__main__":
		__UpperCAmelCase						=			'''This is my Python script that emulates the Enigma machine from WWII.'''
		__UpperCAmelCase						=			(1, 1, 1)
		__UpperCAmelCase						=			'''pictures'''
		__UpperCAmelCase						=			(rotora, rotora, rotora)
		__UpperCAmelCase						=			enigma(message, rotor_pos, rotor_sel, pb)

		print('''Encrypted message:''', en)
		print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))






"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__UpperCAmelCase						=			logging.get_logger(__name__)






def      lowercase__ (					lowerCAmelCase__   :			Union[tf.Tensor, np.ndarray]			)    ->			List[int]:



			'''simple docstring'''
			if isinstance(lowerCAmelCase__							,			np.ndarray			):
						return list(tensor.shape			)

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)

			if tensor.shape == tf.TensorShape(lowerCAmelCase__			):
						return dynamic

			a__  :	Union[str, Any]		 =			tensor.shape.as_list()

			return [dynamic[i] if s is None else s for i, s in enumerate(lowerCAmelCase__			)]






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			Optional[int] = None							,			lowerCAmelCase__   :			Optional[str] = None			)    ->			tf.Tensor:



			'''simple docstring'''
			return tf.nn.softmax(logits=logits + 1E-9							,			axis=lowerCAmelCase__							,			name=lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			List[str]							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Union[str, Any]=1E-5							,			lowerCAmelCase__   :			str=-1			)    ->			int:



			'''simple docstring'''
			# This is a very simplified functional layernorm, designed to duplicate
			# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
			# models in Transformers.

			if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCAmelCase__							,			lowerCAmelCase__			):
						raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis."			)

			# Get mean and variance on the axis to be normalized
			a__ ,	a__  :	Dict		 =			tf.nn.moments(lowerCAmelCase__							,			axes=[axis]							,			keepdims=lowerCAmelCase__			)

			if axis != -1:
						# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
						# on every dimension except axis
						a__  :	Dict		 =			[1] * inputs.shape.rank
						a__  :	Dict		 =			shape_list(lowerCAmelCase__			)[axis]
						a__  :	Any		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)
						a__  :	List[Any]		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)

			# Compute layer normalization using the batch_normalization
			# function.
			a__  :	List[str]		 =			tf.nn.batch_normalization(
			    lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__							,			offset=lowerCAmelCase__							,			scale=lowerCAmelCase__							,			variance_epsilon=lowerCAmelCase__							,			)
			return outputs






def      lowercase__ (					lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			Any=0							,			lowerCAmelCase__   :			List[str]=-1			)    ->			List[str]:



			'''simple docstring'''
			# Replicates the behavior of torch.flatten in TF

			# If end_dim or start_dim is negative, count them from the end
			if end_dim < 0:
						end_dim += input.shape.rank
			if start_dim < 0:
						start_dim += input.shape.rank

			if start_dim == end_dim:
						return input

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)
			a__  :	str		 =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]			)
			a__  :	Union[str, Any]		 =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]							,			axis=0			)
			return tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor			)    ->			tf.Tensor:



			'''simple docstring'''
			if not isinstance(lowerCAmelCase__							,			tf.Tensor			):
						a__  :	Optional[Any]		 =			tf.convert_to_tensor(lowerCAmelCase__			)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						a__  :	Tuple		 =			encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						a__  :	int		 =			encoder_attention_mask[:, None, None, :]
			# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
			# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
			# /transformer/transformer_layers.py#L270
			# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
			# encoder_extended_attention_mask.transpose(-1, -2))
			a__  :	int		 =			(
			    tf.cast(1							,			encoder_attention_mask.dtype			) - encoder_extended_attention_mask
			) * encoder_extended_attention_mask.dtype.min

			return encoder_extended_attention_mask






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			str = "input_ids"			)    ->			None:



			'''simple docstring'''
			tf.debugging.assert_less(
			    lowerCAmelCase__							,			tf.cast(lowerCAmelCase__							,			dtype=tensor.dtype			)							,			message=(
			        F"The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCAmelCase__			)}) must be smaller than the embedding "
			        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
			    )							,			)






def      lowercase__ (					lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			Dict			)    ->			Tuple:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			6_4_5_1_2
			# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
			# because in that case even chunking the array would not make the saving
			# possible.
			a__  :	Optional[Any]		 =			[x for x in data if len(lowerCAmelCase__			) > HDF5_OBJECT_HEADER_LIMIT]

			# Expecting this to never be true.
			if bad_attributes:
						raise RuntimeError(
						    "The following attributes cannot be saved to HDF5 file because "
						    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
						    F"bytes: {bad_attributes}"			)

			a__  :	List[str]		 =			np.asarray(lowerCAmelCase__			)

			a__  :	List[str]		 =			1
			a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			# This will never loop forever thanks to the test above.
			while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data			):
						num_chunks += 1
						a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(lowerCAmelCase__			):
									a__  :	List[Any]		 =			chunk_data
			else:
						a__  :	List[str]		 =			data






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			Tuple			)    ->			Tuple:



			'''simple docstring'''
			if name in group.attrs:
						a__  :	str		 =			[n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs[name]]
			else:
						a__  :	str		 =			[]
						a__  :	Any		 =			0
						while "%s%d" % (name, chunk_id) in group.attrs:
									data.extend(
									    [n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs["%s%d" % (name, chunk_id)]]			)
									chunk_id += 1
			return data






def      lowercase__ (					lowerCAmelCase__   :			Tuple			)    ->			List[Any]:



			'''simple docstring'''

			def _expand_single_ad_tensor(lowerCAmelCase__   :			List[str]			):
						if isinstance(lowerCAmelCase__							,			tf.Tensor			) and t.shape.rank == 1:
									return tf.expand_dims(lowerCAmelCase__							,			axis=-1			)
						return t

			return tf.nest.map_structure(_expand_single_ad_tensor							,			lowerCAmelCase__			)