




import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation

UpperCAmelCase__    :							str       		=     logging.get_logger(__name__)

UpperCAmelCase__    :							Any       		=     {'vocab_file': 'tokenizer.model'}

UpperCAmelCase__    :							List[str]       		=     {
    'vocab_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model',
    },
    'tokenizer_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json',
    },
}
UpperCAmelCase__    :							int       		=     {
    'hf-internal-testing/llama-tokenizer': 2048,
}
UpperCAmelCase__    :							Optional[int]       		=     '▁'

UpperCAmelCase__		,  UpperCAmelCase__    :							int       		=     '[INST]', '[/INST]'
UpperCAmelCase__		,  UpperCAmelCase__    :							Tuple       		=     '<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
UpperCAmelCase__    :							Any       		=     'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'

class   UpperCAmelCase    (      A ):
   __SCREAMING_SNAKE_CASE		:				Tuple      					=       VOCAB_FILES_NAMES
   __SCREAMING_SNAKE_CASE		:				List[str]      					=       PRETRAINED_VOCAB_FILES_MAP
   __SCREAMING_SNAKE_CASE		:				str      					=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __SCREAMING_SNAKE_CASE		:				str      					=       ["input_ids", "attention_mask"]






   def __init__(						self :							Dict    ,       UpperCamelCase_ :							Union[str, Any]    ,       UpperCamelCase_ :							Any="<unk>"    ,       UpperCamelCase_ :							str="<s>"    ,       UpperCamelCase_ :							Tuple="</s>"    ,       UpperCamelCase_ :							Optional[Any]=None    ,       UpperCamelCase_ :							Optional[Dict[str, Any]] = None    ,       UpperCamelCase_ :							str=True    ,       UpperCamelCase_ :							Optional[int]=False    ,       UpperCamelCase_ :							str=False    ,       UpperCamelCase_ :							Optional[int]=True    ,       **UpperCamelCase_ :							Dict    ,       )->      List[Any]:
     _lowercase:			Optional[int]      =     {} if sp_model_kwargs is None else sp_model_kwargs
     _lowercase:			List[Any]      =     AddedToken(UpperCamelCase_    ,       lstrip=UpperCamelCase_    ,       rstrip=UpperCamelCase_  ) if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else bos_token
     _lowercase:			str      =     AddedToken(UpperCamelCase_    ,       lstrip=UpperCamelCase_    ,       rstrip=UpperCamelCase_  ) if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else eos_token
     _lowercase:			Any      =     AddedToken(UpperCamelCase_    ,       lstrip=UpperCamelCase_    ,       rstrip=UpperCamelCase_  ) if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else unk_token
     _lowercase:			str      =     AddedToken(UpperCamelCase_    ,       lstrip=UpperCamelCase_    ,       rstrip=UpperCamelCase_  ) if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else pad_token
     super().__init__(
         bos_token=UpperCamelCase_    ,       eos_token=UpperCamelCase_    ,       unk_token=UpperCamelCase_    ,       pad_token=UpperCamelCase_    ,       add_bos_token=UpperCamelCase_    ,       add_eos_token=UpperCamelCase_    ,       sp_model_kwargs=self.sp_model_kwargs    ,       clean_up_tokenization_spaces=UpperCamelCase_    ,       legacy=UpperCamelCase_    ,       **UpperCamelCase_    ,       )
     if legacy:
       logger.warning_once(
           f'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'
           ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'  )
     _lowercase:			Dict      =     legacy
     _lowercase:			Optional[int]      =     vocab_file
     _lowercase:			Optional[int]      =     add_bos_token
     _lowercase:			List[str]      =     add_eos_token
     _lowercase:			Union[str, Any]      =     spm.SentencePieceProcessor(**self.sp_model_kwargs  )
     self.sp_model.Load(UpperCamelCase_  )






   def __getstate__(						self :							Optional[Any]  )->      int:
     _lowercase:			int      =     self.__dict__.copy()
     _lowercase:			Optional[Any]      =     None
     _lowercase:			List[Any]      =     self.sp_model.serialized_model_proto()
     return state






   def __setstate__(						self :							List[Any]    ,       UpperCamelCase_ :							Dict  )->      Any:
     _lowercase:			Union[str, Any]      =     d
     _lowercase:			int      =     spm.SentencePieceProcessor(**self.sp_model_kwargs  )
     self.sp_model.LoadFromSerializedProto(self.sp_model_proto  )






   @property
   def 			_a    (						self :							Dict  )->      Union[str, Any]:
     return self.sp_model.get_piece_size()






   def 			_a    (						self :							List[Any]  )->      Optional[int]:
     _lowercase:			Dict      =     {self.convert_ids_to_tokens(UpperCamelCase_  ): i for i in range(self.vocab_size  )}
     vocab.update(self.added_tokens_encoder  )
     return vocab






   def 			_a    (						self :							Any    ,       UpperCamelCase_ :							Optional[Any]    ,       **UpperCamelCase_ :							str  )->      List[str]:
     # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
     # the beginning of the text
     if not self.legacy:
       _lowercase:			Union[str, Any]      =     SPIECE_UNDERLINE + text.replace(UpperCamelCase_    ,       ' '  )
     return super().tokenize(UpperCamelCase_    ,       **UpperCamelCase_  )






   def 			_a    (						self :							str    ,       UpperCamelCase_ :							List[str]  )->      Tuple:
     if not self.legacy:
       _lowercase:			Union[str, Any]      =     text.startswith(UpperCamelCase_  )
       if is_first:
         _lowercase:			List[str]      =     text[1:]

     _lowercase:			str      =     self.sp_model.encode(UpperCamelCase_    ,       out_type=UpperCamelCase_  )

     if not self.legacy and not is_first and not text.startswith(' '  ) and tokens[0].startswith(UpperCamelCase_  ):
       _lowercase:			str      =     ([tokens[0][1:]] if len(tokens[0]  ) > 1 else []) + tokens[1:]
     return tokens






   def 			_a    (						self :							List[str]    ,       UpperCamelCase_ :							int  )->      Union[str, Any]:
     return self.sp_model.piece_to_id(UpperCamelCase_  )






   def 			_a    (						self :							Tuple    ,       UpperCamelCase_ :							List[str]  )->      Union[str, Any]:
     _lowercase:			Tuple      =     self.sp_model.IdToPiece(UpperCamelCase_  )
     return token






   def 			_a    (						self :							str    ,       UpperCamelCase_ :							List[Any]  )->      List[Any]:
     _lowercase:			Optional[int]      =     []
     _lowercase:			List[str]      =     ''
     _lowercase:			str      =     False
     for i, token in enumerate(UpperCamelCase_  ):
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
         if not prev_is_special and i != 0:
           out_string += " "
         out_string += self.sp_model.decode(UpperCamelCase_  ) + token
         _lowercase:			Dict      =     True
         _lowercase:			str      =     []
       else:
         current_sub_tokens.append(UpperCamelCase_  )
         _lowercase:			Optional[Any]      =     False
     out_string += self.sp_model.decode(UpperCamelCase_  )
     return out_string






   def 			_a    (						self :							List[str]    ,       UpperCamelCase_ :							str    ,       UpperCamelCase_ :							Optional[str] = None  )->      Tuple[str]:
     if not os.path.isdir(UpperCamelCase_  ):
       logger.error(f'Vocabulary path ({save_directory}) should be a directory'  )
       return
     _lowercase:			Optional[int]      =     os.path.join(
         UpperCamelCase_    ,       (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )

     if os.path.abspath(self.vocab_file  ) != os.path.abspath(UpperCamelCase_  ) and os.path.isfile(self.vocab_file  ):
       copyfile(self.vocab_file    ,       UpperCamelCase_  )
     elif not os.path.isfile(self.vocab_file  ):
       with open(UpperCamelCase_    ,       'wb'  ) as fi:
         _lowercase:			Any      =     self.sp_model.serialized_model_proto()
         fi.write(UpperCamelCase_  )

     return (out_vocab_file,)






   def 			_a    (						self :							str    ,       UpperCamelCase_ :							Union[str, Any]    ,       UpperCamelCase_ :							Optional[Any]=None  )->      Dict:
     _lowercase:			List[str]      =     [self.bos_token_id] if self.add_bos_token else []
     _lowercase:			Tuple      =     [self.eos_token_id] if self.add_eos_token else []

     _lowercase:			Any      =     bos_token_id + token_ids_a + eos_token_id

     if token_ids_a is not None:
       _lowercase:			List[str]      =     output + bos_token_id + token_ids_a + eos_token_id

     return output






   def 			_a    (						self :							Dict    ,       UpperCamelCase_ :							List[int]    ,       UpperCamelCase_ :							Optional[List[int]] = None    ,       UpperCamelCase_ :							bool = False  )->      List[int]:
     if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=UpperCamelCase_    ,       token_ids_a=UpperCamelCase_    ,       already_has_special_tokens=UpperCamelCase_  )

     _lowercase:			List[str]      =     [1] if self.add_bos_token else []
     _lowercase:			List[str]      =     [1] if self.add_eos_token else []

     if token_ids_a is None:
       return bos_token_id + ([0] * len(UpperCamelCase_  )) + eos_token_id
     return (
         bos_token_id
         + ([0] * len(UpperCamelCase_  ))
         + eos_token_id
         + bos_token_id
         + ([0] * len(UpperCamelCase_  ))
         + eos_token_id
     )






   def 			_a    (						self :							Tuple    ,       UpperCamelCase_ :							List[int]    ,       UpperCamelCase_ :							Optional[List[int]] = None  )->      List[int]:
     _lowercase:			List[str]      =     [self.bos_token_id] if self.add_bos_token else []
     _lowercase:			Any      =     [self.eos_token_id] if self.add_eos_token else []

     _lowercase:			int      =     [0] * len(bos_token_id + token_ids_a + eos_token_id  )

     if token_ids_a is not None:
       output += [1] * len(bos_token_id + token_ids_a + eos_token_id  )

     return output






   def 			_a    (						self :							Union[str, Any]    ,       UpperCamelCase_ :							"Conversation"  )->      List[int]:
     _lowercase:			Tuple      =     list(conversation.iter_texts()  )
     if not all([is_user for is_user, msg in dialogue[::2]]  ) or not all(
         [not is_user for is_user, msg in dialogue[1::2]]  ):
       raise ValueError(
           'The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'  )

     _lowercase:			List[int]      =     []
     if len(conversation.past_user_inputs  ) > 0:
       if not conversation.past_user_inputs[0].startswith(UpperCamelCase_  ) or E_SYS not in conversation.past_user_inputs[0]:
         _lowercase:			Optional[Any]      =     (
             B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
         )
     elif not dialogue[0][1].startswith(UpperCamelCase_  ) or E_SYS not in dialogue[0][1]:
       _lowercase:			List[Any]      =     (dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

     dialog_tokens += sum(
         [
             [self.bos_token_id]
             + self.encode(
                 f'{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '    ,       add_special_tokens=UpperCamelCase_  )
             + [self.eos_token_id]
             for prompt, answer in zip(dialogue[::2]    ,       dialogue[1::2]  )
         ]    ,       []    ,       )
     if not (dialogue[-1][0]):
       raise ValueError(f'Last message must be from user, got {dialogue[-1]["role"]}'  )
     dialog_tokens += [self.bos_token_id] + self.encode(
         f'{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'    ,       add_special_tokens=UpperCamelCase_  )
     return dialog_tokens






from __future__ import annotations

class   UpperCAmelCase    :






   def __init__(						self :							List[Any]    ,       UpperCamelCase_ :							int  )->      None:
     _lowercase:			Optional[Any]      =     data
     _lowercase:			Optional[int]      =     None

class   UpperCAmelCase    :






   def __init__(						self :							Optional[Any]  )->      Union[str, Any]:
     _lowercase:			List[str]      =     None






   def 			_a    (						self :							List[Any]    ,       UpperCamelCase_ :							int  )->      int:
     _lowercase:			Any      =     Node(UpperCamelCase_  )
     _lowercase:			List[Any]      =     self.head
     _lowercase:			List[str]      =     new_node
     return self.head.data






   def 			_a    (						self :							Tuple  )->      int | None:
     _lowercase:			List[str]      =     self.head
     _lowercase:			str      =     self.head
     if self.head:
       while fast_pointer and fast_pointer.next:
         _lowercase:			Optional[int]      =     fast_pointer.next.next
         _lowercase:			Tuple      =     slow_pointer.next
       return slow_pointer.data
     else:
       print('No element found.'  )
       return None


if __name__ == "__main__":
   UpperCAmelCase__    :							Union[str, Any]       		=     LinkedList()
   for _ in range(int(input().strip())):
      UpperCAmelCase__    :							List[Any]       		=     int(input().strip())
      link.push(data)
   print(link.middle_element())
