



'''simple docstring'''





import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",
    datefmt="""%m/%d/%Y %H:%M:%S""",
    level=logging.INFO,
)
A			:   str			=      logging.getLogger(__name__)

A			:   List[str]			=      int(10_000)  # Hardcoded max length to avoid infinite loop

A			:   Dict			=      {
    """gpt2""": (GPTaLMHeadModel, GPTaTokenizer),
    """ctrl""": (CTRLLMHeadModel, CTRLTokenizer),
    """openai-gpt""": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    """xlnet""": (XLNetLMHeadModel, XLNetTokenizer),
    """transfo-xl""": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    """xlm""": (XLMWithLMHeadModel, XLMTokenizer),
    """gptj""": (GPTJForCausalLM, AutoTokenizer),
    """bloom""": (BloomForCausalLM, BloomTokenizerFast),
    """llama""": (LlamaForCausalLM, LlamaTokenizer),
    """opt""": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
A			:   str			=      """In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
def 		_a   (  lowerCamelCase_							):
   np.random.seed(args.seed							)
   torch.manual_seed(args.seed							)
   if args.n_gpu > 0:
      torch.cuda.manual_seed_all(args.seed							)
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   if args.temperature > 0.7:
      logger.info('''CTRL typically works better with lower temperatures (and lower top_k).'''							)

   snake_case   :							Any						  =tokenizer.encode(_lowerCAmelCase					,						add_special_tokens=_lowerCAmelCase							)
   if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()							):
      logger.info('''WARNING! You are not starting your generation from a control code so you won\'t get good results'''							)
   return prompt_text
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   # kwargs = {"language": None, "mask_token_id": None}

   # Set the language
   snake_case   :							List[Any]						  =hasattr(model.config					,						'''use_lang_emb'''							) and model.config.use_lang_emb
   if hasattr(model.config					,						'''lang2id'''							) and use_lang_emb:
      snake_case   :							List[str]						  =model.config.langaid.keys()
      if args.xlm_language in available_languages:
         snake_case   :							List[str]						  =args.xlm_language
      else:
         snake_case   :							str						  =None
         while language not in available_languages:
            snake_case   :							Any						  =input('''Using XLM. Select language in ''' + str(list(_lowerCAmelCase							)							) + ''' >>> '''							)

      snake_case   :							str						  =model.config.langaid[language]
      # kwargs["language"] = tokenizer.lang2id[language]

   # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
   # XLM masked-language modeling (MLM) models need masked token
   # is_xlm_mlm = "mlm" in args.model_name_or_path
   # if is_xlm_mlm:
   #     kwargs["mask_token_id"] = tokenizer.mask_token_id

   return prompt_text
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   snake_case   :							Any						  =args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
   snake_case   :							Any						  =prefix + prompt_text
   return prompt_text
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   snake_case   :							List[str]						  =args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
   snake_case   :							List[Any]						  =prefix + prompt_text
   return prompt_text


A			:   Any			=      {
    """ctrl""": prepare_ctrl_input,
    """xlm""": prepare_xlm_input,
    """xlnet""": prepare_xlnet_input,
    """transfo-xl""": prepare_transfoxl_input,
}
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_							):
   if length < 0 and max_sequence_length > 0:
      snake_case   :							List[Any]						  =max_sequence_length
   elif 0 < max_sequence_length < length:
      snake_case   :							Union[str, Any]						  =max_sequence_length  # No generation bigger than model size
   elif length < 0:
      snake_case   :							str						  =MAX_LENGTH  # avoid infinite loop
   return length
def 		_a   (  lowerCamelCase_							):
   snake_case   :							Optional[Any]						  =None
   if hasattr(_lowerCAmelCase					,						'''hidden_size'''							):
      snake_case   :							List[str]						  =model_config.hidden_size
   elif hasattr(_lowerCAmelCase					,						'''n_embed'''							):
      snake_case   :							Union[str, Any]						  =model_config.n_embed
   elif hasattr(_lowerCAmelCase					,						'''n_embd'''							):
      snake_case   :							Any						  =model_config.n_embd

   snake_case   :							List[Any]						  =None
   if hasattr(_lowerCAmelCase					,						'''num_attention_heads'''							):
      snake_case   :							int						  =model_config.num_attention_heads
   elif hasattr(_lowerCAmelCase					,						'''n_head'''							):
      snake_case   :							Optional[Any]						  =model_config.n_head

   if embedding_size is None or num_head is None or num_head == 0:
      raise ValueError('''Check the model config'''							)

   snake_case   :							Optional[Any]						  =int(embedding_size / num_head							)
   if hasattr(_lowerCAmelCase					,						'''n_layer'''							):
      snake_case   :							Tuple						  =model_config.n_layer
   elif hasattr(_lowerCAmelCase					,						'''num_hidden_layers'''							):
      snake_case   :							Optional[Any]						  =model_config.num_hidden_layers
   else:
      raise ValueError('''Number of hidden layers couldn\'t be determined from the model config'''							)

   return num_layer, num_head, num_embedding_size_per_head
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   snake_case  ,    snake_case  ,    snake_case   :							Tuple						  =sparse_model_config(model.config							)
   if model.config.model_type == "bloom":
      snake_case   :							Union[str, Any]						  =tuple(
          (
              torch.empty(int(num_attention_heads * batch_size							)					,						_lowerCAmelCase					,						_lowerCAmelCase							)
              .to(model.dtype							)
              .to(model.device							),
              torch.empty(int(num_attention_heads * batch_size							)					,						_lowerCAmelCase					,						_lowerCAmelCase							)
              .to(model.dtype							)
              .to(model.device							),
          )
          for _ in range(_lowerCAmelCase							)							)
   else:
      snake_case   :							Optional[Any]						  =tuple(
          (
              torch.empty(_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase							)
              .to(model.dtype							)
              .to(model.device							),
              torch.empty(_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase							)
              .to(model.dtype							)
              .to(model.device							),
          )
          for _ in range(_lowerCAmelCase							)							)
   return past_key_values
def 		_a   (  lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_							):
   snake_case   :							Union[str, Any]						  =len(_lowerCAmelCase							)
   snake_case   :							Optional[int]						  =tokenizer.batch_encode_plus(_lowerCAmelCase					,						return_tensors='''pt'''							)
   snake_case   :							Optional[int]						  =dummy_input.to(model.device							)
   if model.config.use_cache:
      snake_case   :							Tuple						  =generate_past_key_values(_lowerCAmelCase					,						_lowerCAmelCase					,						1							)
   snake_case   :							Dict						  =torch.cat(
       [
           torch.zeros(dummy_input['''attention_mask'''].shape[0]					,						1							)
           .to(dummy_input['''attention_mask'''].dtype							)
           .to(model.device							),
           dummy_input['''attention_mask'''],
       ]					,						-1					,						)
   return dummy_input





class 							lowerCAmelCase_		(	a_						):
    __UpperCAmelCase							=	('_optimized', '_default')





    def __init__(    self    :    str,    _snake_case    :    int,    _snake_case    :    Tuple     ):



       '''simple docstring'''







       snake_case   :							str						  =optimized
       snake_case   :							Any						  =default





    def __call__(    self    :    List[str],    *_snake_case    :    int,    **_snake_case    :    Union[str, Any]     ):



       '''simple docstring'''







       if kwargs["past_key_values"] is None and self._default.config.use_cache:
          snake_case   :							List[str]						  =generate_past_key_values(self._default,    kwargs['''input_ids'''].shape[0],    0     )
       kwargs.pop('''position_ids''',    snake_case__     )
       for k in list(kwargs.keys()     ):
          if kwargs[k] is None or isinstance(kwargs[k],    snake_case__     ):
             kwargs.pop(snake_case__     )
       snake_case   :							Dict						  =self._optimized(**snake_case__     )
       snake_case   :							str						  =outputs[0]
       snake_case   :							Any						  =outputs[1]
       snake_case   :							List[str]						  =CausalLMOutputWithPast(
           loss=snake_case__,    logits=snake_case__,    past_key_values=snake_case__,    hidden_states=snake_case__,    attentions=snake_case__,    )
       return fixed_output





    def __getattr__(    self    :    Optional[int],    _snake_case    :    List[str]     ):



       '''simple docstring'''







       return getattr(self._default,    snake_case__     )





    def 					__snake_case       (    self    :    Tuple,    _snake_case    :    Tuple,    _snake_case    :    Optional[Any]=None,    _snake_case    :    Optional[Any]=None,    _snake_case    :    str=None,    **_snake_case    :    Optional[Any]     ):



       '''simple docstring'''







       return self._default.prepare_inputs_for_generation(
           snake_case__,    past_key_values=snake_case__,    inputs_embeds=snake_case__,    use_cache=snake_case__,    **snake_case__     )






    def 					__snake_case       (    self    :    List[Any],    _snake_case    :    Optional[Any],    _snake_case    :    Any     ):



       '''simple docstring'''







       return self._default._reorder_cache(snake_case__,    snake_case__     )




def 		_a   (  ):
   snake_case   :							Optional[int]						  =argparse.ArgumentParser()
   parser.add_argument(
       '''--model_type'''					,						default=_lowerCAmelCase					,						type=_lowerCAmelCase					,						required=_lowerCAmelCase					,						help='''Model type selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys()							)					,						)
   parser.add_argument(
       '''--model_name_or_path'''					,						default=_lowerCAmelCase					,						type=_lowerCAmelCase					,						required=_lowerCAmelCase					,						help='''Path to pre-trained model or shortcut name selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys()							)					,						)

   parser.add_argument('''--prompt'''					,						type=_lowerCAmelCase					,						default=''''''							)
   parser.add_argument('''--length'''					,						type=_lowerCAmelCase					,						default=20							)
   parser.add_argument('''--stop_token'''					,						type=_lowerCAmelCase					,						default=_lowerCAmelCase					,						help='''Token at which text generation is stopped'''							)

   parser.add_argument(
       '''--temperature'''					,						type=_lowerCAmelCase					,						default=1.0					,						help='''temperature of 1.0 has no effect, lower tend toward greedy sampling'''					,						)
   parser.add_argument(
       '''--repetition_penalty'''					,						type=_lowerCAmelCase					,						default=1.0					,						help='''primarily useful for CTRL model; in that case, use 1.2'''							)
   parser.add_argument('''--k'''					,						type=_lowerCAmelCase					,						default=0							)
   parser.add_argument('''--p'''					,						type=_lowerCAmelCase					,						default=0.9							)

   parser.add_argument('''--prefix'''					,						type=_lowerCAmelCase					,						default=''''''					,						help='''Text added prior to input.'''							)
   parser.add_argument('''--padding_text'''					,						type=_lowerCAmelCase					,						default=''''''					,						help='''Deprecated, the use of `--prefix` is preferred.'''							)
   parser.add_argument('''--xlm_language'''					,						type=_lowerCAmelCase					,						default=''''''					,						help='''Optional language when used with the XLM model.'''							)

   parser.add_argument('''--seed'''					,						type=_lowerCAmelCase					,						default=42					,						help='''random seed for initialization'''							)
   parser.add_argument('''--no_cuda'''					,						action='''store_true'''					,						help='''Avoid using CUDA when available'''							)
   parser.add_argument('''--num_return_sequences'''					,						type=_lowerCAmelCase					,						default=1					,						help='''The number of samples to generate.'''							)
   parser.add_argument(
       '''--fp16'''					,						action='''store_true'''					,						help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''					,						)
   parser.add_argument('''--jit'''					,						action='''store_true'''					,						help='''Whether or not to use jit trace to accelerate inference'''							)
   snake_case   :							List[str]						  =parser.parse_args()

   snake_case   :							Tuple						  =torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''							)
   snake_case   :							Optional[Any]						  =0 if args.no_cuda else torch.cuda.device_count()

   logger.warning(F'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''							)

   set_seed(_lowerCAmelCase							)

   # Initialize the model and tokenizer
   try:
      snake_case   :							Optional[int]						  =args.model_type.lower()
      snake_case  ,    snake_case   :							Optional[int]						  =MODEL_CLASSES[args.model_type]
   except KeyError:
      raise KeyError('''the model {} you specified is not supported. You are welcome to add it and open a PR :)'''							)

   snake_case   :							int						  =tokenizer_class.from_pretrained(args.model_name_or_path							)
   if tokenizer.pad_token is None:
      snake_case   :							str						  =tokenizer.eos_token
   snake_case   :							Tuple						  =model_class.from_pretrained(args.model_name_or_path							)
   model.to(args.device							)

   if args.fpaa:
      model.half()
   snake_case   :							str						  =getattr(model.config					,						'''max_position_embeddings'''					,						0							)
   snake_case   :							List[Any]						  =adjust_length_to_model(args.length					,						max_sequence_length=_lowerCAmelCase							)
   logger.info(_lowerCAmelCase							)

   snake_case   :							Union[str, Any]						  =args.prompt if args.prompt else input('''Model prompt >>> '''							)

   # Different models need different input formatting and/or extra arguments
   snake_case   :							List[Any]						  =args.model_type in PREPROCESSING_FUNCTIONS.keys()
   if requires_preprocessing:
      snake_case   :							Optional[Any]						  =PREPROCESSING_FUNCTIONS.get(args.model_type							)
      snake_case   :							str						  =prepare_input(_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase							)

      if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
         snake_case   :							Dict						  ={'''add_space_before_punct_symbol''': True}
      else:
         snake_case   :							Dict						  ={}

      snake_case   :							Tuple						  =tokenizer.encode(
          _lowerCAmelCase					,						add_special_tokens=_lowerCAmelCase					,						return_tensors='''pt'''					,						**_lowerCAmelCase							)
   else:
      snake_case   :							Union[str, Any]						  =args.prefix if args.prefix else args.padding_text
      snake_case   :							Tuple						  =tokenizer.encode(prefix + prompt_text					,						add_special_tokens=_lowerCAmelCase					,						return_tensors='''pt'''							)
   snake_case   :							List[str]						  =encoded_prompt.to(args.device							)

   if encoded_prompt.size()[-1] == 0:
      snake_case   :							Optional[int]						  =None
   else:
      snake_case   :							int						  =encoded_prompt

   if args.jit:
      snake_case   :							str						  =['''enable jit''']
      snake_case   :							List[Any]						  =prepare_jit_inputs(_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase							)
      torch._C._jit_set_texpr_fuser_enabled(_lowerCAmelCase							)
      snake_case   :							Optional[int]						  =False
      if hasattr(_lowerCAmelCase					,						'''forward'''							):
         snake_case   :							Dict						  =inspect.signature(model.forward							)
      else:
         snake_case   :							Optional[int]						  =inspect.signature(model.__call__							)
      snake_case   :							int						  =tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(_lowerCAmelCase					,						_lowerCAmelCase							) is not None							)
      snake_case   :							List[Any]						  =torch.jit.trace(_lowerCAmelCase					,						_lowerCAmelCase					,						strict=_lowerCAmelCase							)
      snake_case   :							Dict						  =torch.jit.freeze(traced_model.eval()							)
      traced_model(*_lowerCAmelCase							)
      traced_model(*_lowerCAmelCase							)

      snake_case   :							Optional[Any]						  =_ModelFallbackWrapper(_lowerCAmelCase					,						_lowerCAmelCase							)

   snake_case   :							Any						  =model.generate(
       input_ids=_lowerCAmelCase					,						max_length=args.length + len(encoded_prompt[0]							)					,						temperature=args.temperature					,						top_k=args.k					,						top_p=args.p					,						repetition_penalty=args.repetition_penalty					,						do_sample=_lowerCAmelCase					,						num_return_sequences=args.num_return_sequences					,						)

   # Remove the batch dimension when returning multiple sequences
   if len(output_sequences.shape							) > 2:
      output_sequences.squeeze_()

   snake_case   :							str						  =[]

   for generated_sequence_idx, generated_sequence in enumerate(_lowerCAmelCase							):
      print(F'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''							)
      snake_case   :							Any						  =generated_sequence.tolist()

      # Decode text
      snake_case   :							Union[str, Any]						  =tokenizer.decode(_lowerCAmelCase					,						clean_up_tokenization_spaces=_lowerCAmelCase							)

      # Remove all text after the stop token
      snake_case   :							List[Any]						  =text[: text.find(args.stop_token							) if args.stop_token else None]

      # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
      snake_case   :							Optional[Any]						  =(
          prompt_text + text[len(tokenizer.decode(encoded_prompt[0]					,						clean_up_tokenization_spaces=_lowerCAmelCase							)							) :]
      )

      generated_sequences.append(_lowerCAmelCase							)
      print(_lowerCAmelCase							)

   return generated_sequences


if __name__ == "__main__":
      main()




'''simple docstring'''





class 							lowerCAmelCase_		:





    def __init__(    self    :    List[Any],    _snake_case    :    Any     ):



       '''simple docstring'''







       snake_case   :							Tuple						  =data
       snake_case   :							int						  =None
       snake_case   :							List[Any]						  =None






    def __str__(    self    :    List[str]     ):



       '''simple docstring'''







       return f'''{self.data}'''





class 							lowerCAmelCase_		:





    def __init__(    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							Optional[int]						  =None
       snake_case   :							int						  =None





    def __iter__(    self    :    List[str]     ):



       '''simple docstring'''







       snake_case   :							str						  =self.head
       while node:
          yield node.data
          snake_case   :							Union[str, Any]						  =node.next





    def __str__(    self    :    List[str]     ):



       '''simple docstring'''







       return "->".join([str(_snake_case     ) for item in self]     )





    def __len__(    self    :    Dict     ):



       '''simple docstring'''







       return sum(1 for _ in self     )





    def 					__snake_case       (    self    :    List[Any],    _snake_case    :    str     ):



       '''simple docstring'''







       self.insert_at_nth(0,    _snake_case     )





    def 					__snake_case       (    self    :    Optional[Any],    _snake_case    :    Dict     ):



       '''simple docstring'''







       self.insert_at_nth(len(self     ),    _snake_case     )





    def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    int,    _snake_case    :    Dict     ):



       '''simple docstring'''







       snake_case   :							Optional[int]						  =len(self     )

       if not 0 <= index <= length:
          raise IndexError('''list index out of range'''     )
       snake_case   :							int						  =Node(_snake_case     )
       if self.head is None:
          snake_case   :							Optional[Any]						  =new_node
       elif index == 0:
          snake_case   :							int						  =new_node
          snake_case   :							Union[str, Any]						  =self.head
          snake_case   :							Optional[int]						  =new_node
       elif index == length:
          snake_case   :							Dict						  =new_node
          snake_case   :							int						  =self.tail
          snake_case   :							Union[str, Any]						  =new_node
       else:
          snake_case   :							Optional[int]						  =self.head
          for _ in range(0,    _snake_case     ):
             snake_case   :							Union[str, Any]						  =temp.next
          snake_case   :							int						  =new_node
          snake_case   :							Union[str, Any]						  =temp.previous
          snake_case   :							List[Any]						  =temp
          snake_case   :							int						  =new_node





    def 					__snake_case       (    self    :    str     ):



       '''simple docstring'''







       return self.delete_at_nth(0     )





    def 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







       return self.delete_at_nth(len(self     ) - 1     )





    def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    int     ):



       '''simple docstring'''







       snake_case   :							Dict						  =len(self     )

       if not 0 <= index <= length - 1:
          raise IndexError('''list index out of range'''     )
       snake_case   :							List[str]						  =self.head  # default first node
       if length == 1:
          snake_case   :							Union[str, Any]						  =None
       elif index == 0:
          snake_case   :							Tuple						  =self.head.next
          snake_case   :							Optional[int]						  =None
       elif index == length - 1:
          snake_case   :							Union[str, Any]						  =self.tail
          snake_case   :							List[str]						  =self.tail.previous
          snake_case   :							int						  =None
       else:
          snake_case   :							int						  =self.head
          for _ in range(0,    _snake_case     ):
             snake_case   :							Any						  =temp.next
          snake_case   :							List[Any]						  =temp
          snake_case   :							Optional[Any]						  =temp.previous
          snake_case   :							int						  =temp.next
       return delete_node.data





    def 					__snake_case       (    self    :    List[Any],    _snake_case    :    Tuple     ):



       '''simple docstring'''







       snake_case   :							List[Any]						  =self.head

       while current.data != data:  # Find the position to delete
          if current.next:
             snake_case   :							Any						  =current.next
          else:  # We have reached the end an no value matches
             raise ValueError('''No data matching given value'''     )

       if current == self.head:
          self.delete_head()

       elif current == self.tail:
          self.delete_tail()

       else:  # Before: 1 <--> 2(current) <--> 3
          snake_case   :							Optional[int]						  =current.next  # 1 --> 3
          snake_case   :							List[Any]						  =current.previous  # 1 <--> 3
       return data






    def 					__snake_case       (    self    :    Any     ):



       '''simple docstring'''







       return len(self     ) == 0




def 		_a   (  ):
   snake_case   :							Optional[Any]						  =DoublyLinkedList()
   assert linked_list.is_empty() is True
   assert str(lowerCamelCase_							) == ""

   try:
      linked_list.delete_head()
      raise AssertionError  # This should not happen.
   except IndexError:
      assert True  # This should happen.

   try:
      linked_list.delete_tail()
      raise AssertionError  # This should not happen.
   except IndexError:
      assert True  # This should happen.

   for i in range(10							):
      assert len(lowerCamelCase_							) == i
      linked_list.insert_at_nth(lowerCamelCase_					,						i + 1							)
   assert str(lowerCamelCase_							) == "->".join(str(lowerCamelCase_							) for i in range(1					,						11							)							)

   linked_list.insert_at_head(0							)
   linked_list.insert_at_tail(11							)
   assert str(lowerCamelCase_							) == "->".join(str(lowerCamelCase_							) for i in range(0					,						12							)							)

   assert linked_list.delete_head() == 0
   assert linked_list.delete_at_nth(9							) == 10
   assert linked_list.delete_tail() == 11
   assert len(lowerCamelCase_							) == 9
   assert str(lowerCamelCase_							) == "->".join(str(lowerCamelCase_							) for i in range(1					,						10							)							)


if __name__ == "__main__":
      from doctest import testmod

      testmod()





