

"""simple docstring"""






import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


snake_case_   :   Tuple        =       '''bart'''
snake_case_   :   List[Any]        =       True



@st.cache(allow_output_mutation=lowerCAmelCase__	)
def   lowercase_	(    ):




					'''simple docstring'''






					if LOAD_DENSE_INDEX:
										UpperCAmelCase			:   Any      =				AutoTokenizer.from_pretrained("yjernite/retribert-base-uncased"	)
										UpperCAmelCase			:   int      =				AutoModel.from_pretrained("yjernite/retribert-base-uncased"	).to("cuda:0"	)
										UpperCAmelCase			:   Union[str, Any]      =				qar_model.eval()
					else:
										UpperCAmelCase      ,							UpperCAmelCase			:   List[str]      =				(None, None)
					if MODEL_TYPE == "bart":
										UpperCAmelCase			:   List[Any]      =				AutoTokenizer.from_pretrained("yjernite/bart_eli5"	)
										UpperCAmelCase			:   Any      =				AutoModelForSeqaSeqLM.from_pretrained("yjernite/bart_eli5"	).to("cuda:0"	)
										UpperCAmelCase			:   Any      =				torch.load("seq2seq_models/eli5_bart_model_blm_2.pth"	)
										sas_model.load_state_dict(save_dict["model"]	)
										UpperCAmelCase			:   Optional[int]      =				sas_model.eval()
					else:
										UpperCAmelCase      ,							UpperCAmelCase			:   int      =				make_qa_sas_model(
										    model_name="t5-small"							,      from_file="seq2seq_models/eli5_t5_model_1024_4.pth"							,      device="cuda:0"	)
					return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)



@st.cache(allow_output_mutation=lowerCAmelCase__	)
def   lowercase_	(    ):




					'''simple docstring'''






					if LOAD_DENSE_INDEX:
										UpperCAmelCase			:   List[Any]      =				faiss.StandardGpuResources()
										UpperCAmelCase			:   List[Any]      =				datasets.load_dataset(path="wiki_snippets"							,      name="wiki40b_en_100_0"	)["train"]
										UpperCAmelCase			:   Any      =				np.memmap(
										    "wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"							,      dtype="float32"							,      mode="r"							,      shape=(wikiaab_passages.num_rows, 1_28)							,      )
										UpperCAmelCase			:   Tuple      =				faiss.IndexFlatIP(1_28	)
										UpperCAmelCase			:   Tuple      =				faiss.index_cpu_to_gpu(lowerCAmelCase__							,      1							,      lowerCAmelCase__	)
										wikiaab_gpu_index_flat.add(lowerCAmelCase__	)  # TODO fix for larger GPU
					else:
										UpperCAmelCase      ,							UpperCAmelCase			:   str      =				(None, None)
					UpperCAmelCase			:   Union[str, Any]      =				Elasticsearch([{"host": "localhost", "port": "9200"}]	)
					return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)



@st.cache(allow_output_mutation=lowerCAmelCase__	)
def   lowercase_	(    ):




					'''simple docstring'''






					UpperCAmelCase			:   str      =				datasets.load_dataset("eli5"							,      name="LFQA_reddit"	)
					UpperCAmelCase			:   List[str]      =				elia["train_eli5"]
					UpperCAmelCase			:   List[str]      =				np.memmap(
					    "eli5_questions_reps.dat"							,      dtype="float32"							,      mode="r"							,      shape=(elia_train.num_rows, 1_28)	)
					UpperCAmelCase			:   List[Any]      =				faiss.IndexFlatIP(1_28	)
					eli5_train_q_index.add(lowerCAmelCase__	)
					return (elia_train, eli5_train_q_index)


snake_case_   :   str        =       load_indexes()
snake_case_   :   List[Any]        =       load_models()
snake_case_   :   List[Any]        =       load_train_data()



def   lowercase_	(    _lowercase       :		Optional[int]							,      _lowercase       :		List[str]=10	):




					'''simple docstring'''






					UpperCAmelCase			:   Optional[int]      =				embed_questions_for_retrieval([question]							,      lowerCAmelCase__							,      lowerCAmelCase__	)
					UpperCAmelCase      ,							UpperCAmelCase			:   str      =				eli5_train_q_index.search(lowerCAmelCase__							,      lowerCAmelCase__	)
					UpperCAmelCase			:   List[Any]      =				[elia_train[int(lowerCAmelCase__	)] for i in I[0]]
					return nn_examples



def   lowercase_	(    _lowercase       :		Union[str, Any]							,      _lowercase       :		Tuple="wiki40b"							,      _lowercase       :		Tuple="dense"							,      _lowercase       :		Any=10	):




					'''simple docstring'''






					if source == "none":
										UpperCAmelCase      ,							UpperCAmelCase			:   Tuple      =				(" <P> ".join(["" for _ in range(11	)]	).strip(), [])
					else:
										if method == "dense":
															UpperCAmelCase      ,							UpperCAmelCase			:   Tuple      =				query_qa_dense_index(
															    lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)
										else:
															UpperCAmelCase      ,							UpperCAmelCase			:   Any      =				query_es_index(
															    lowerCAmelCase__							,      lowerCAmelCase__							,      index_name="english_wiki40b_snippets_100w"							,      n_results=lowerCAmelCase__							,      )
					UpperCAmelCase			:   Any      =				[
					    (res["article_title"], res["section_title"].strip(), res["score"], res["passage_text"]) for res in hit_lst
					]
					UpperCAmelCase			:   Tuple      =				"question: {} context: {}".format(lowerCAmelCase__							,      lowerCAmelCase__	)
					return question_doc, support_list



@st.cache(
    hash_funcs={
        torch.Tensor: (lambda _lowercase	: None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowercase	: None),
    }	)
def   lowercase_	(    _lowercase       :		int							,      _lowercase       :		Tuple							,      _lowercase       :		str							,      _lowercase       :		List[Any]=64							,      _lowercase       :		List[Any]=2_56							,      _lowercase       :		Union[str, Any]=False							,      _lowercase       :		List[str]=2							,      _lowercase       :		List[str]=0.9_5							,      _lowercase       :		int=0.8	):




					'''simple docstring'''






					with torch.no_grad():
										UpperCAmelCase			:   List[str]      =				qa_sas_generate(
										    lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      num_answers=1							,      num_beams=lowerCAmelCase__							,      min_len=lowerCAmelCase__							,      max_len=lowerCAmelCase__							,      do_sample=lowerCAmelCase__							,      temp=lowerCAmelCase__							,      top_p=lowerCAmelCase__							,      top_k=lowerCAmelCase__							,      max_input_length=10_24							,      device="cuda:0"							,      )[0]
					return (answer, support_list)


st.title("""Long Form Question Answering with ELI5""")

# Start sidebar
snake_case_   :   Union[str, Any]        =       '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'''
snake_case_   :   Tuple        =       '''
<html>
  <head>
    <style>
      .img-container {
        padding-left: 90px;
        padding-right: 90px;
        padding-top: 50px;
        padding-bottom: 50px;
        background-color: #f0f3f9;
      }
    </style>
  </head>
  <body>
    <span class="img-container"> <!-- Inline parent element -->
      %s
    </span>
  </body>
</html>
''' % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
snake_case_   :   str        =       '''
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
'''
st.sidebar.markdown(description, unsafe_allow_html=True)

snake_case_   :   Dict        =       [
    '''Answer the question''',
    '''View the retrieved document only''',
    '''View the most similar ELI5 question and answer''',
    '''Show me everything, please!''',
]
snake_case_   :   Optional[Any]        =       st.sidebar.checkbox("""Demo options""")
if demo_options:
	snake_case_   :   List[str]        =       st.sidebar.selectbox(
	    """""",
	    action_list,
	    index=3,
	)
	snake_case_   :   List[Any]        =       action_list.index(action_st)
	snake_case_   :   List[str]        =       st.sidebar.selectbox(
	    """""",
	    ["""Show full text of passages""", """Show passage section titles"""],
	    index=0,
	)
	snake_case_   :   Union[str, Any]        =       show_type == '''Show full text of passages'''
else:
	snake_case_   :   Optional[int]        =       3
	snake_case_   :   Tuple        =       True

snake_case_   :   Dict        =       st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
	snake_case_   :   Optional[int]        =       '''
    ### Information retriever options

    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
    '''
	st.sidebar.markdown(retriever_info)
	snake_case_   :   int        =       st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
	snake_case_   :   Dict        =       st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
	snake_case_   :   List[str]        =       '''wiki40b'''
	snake_case_   :   int        =       '''dense'''

snake_case_   :   str        =       '''beam'''
snake_case_   :   List[Any]        =       2
snake_case_   :   Union[str, Any]        =       6_4
snake_case_   :   List[str]        =       2_5_6
snake_case_   :   Optional[int]        =       None
snake_case_   :   Tuple        =       None
snake_case_   :   str        =       st.sidebar.checkbox("""Generation options""")
if generate_options:
	snake_case_   :   Dict        =       '''
    ### Answer generation options

    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
    **beam** search, or **sample** from the decoder\'s output probabilities.
    '''
	st.sidebar.markdown(generate_info)
	snake_case_   :   Optional[Any]        =       st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
	snake_case_   :   Optional[Any]        =       st.sidebar.slider(
	    """Minimum generation length""", min_value=8, max_value=2_5_6, value=6_4, step=8, format=None, key=None
	)
	snake_case_   :   Any        =       st.sidebar.slider(
	    """Maximum generation length""", min_value=6_4, max_value=5_1_2, value=2_5_6, step=1_6, format=None, key=None
	)
	if sampled == "beam":
		snake_case_   :   int        =       st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
	else:
		snake_case_   :   Optional[int]        =       st.sidebar.slider(
		    """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
		)
		snake_case_   :   Optional[int]        =       st.sidebar.slider(
		    """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
		)
		snake_case_   :   Any        =       None

# start main text
snake_case_   :   Dict        =       [
    '''<MY QUESTION>''',
    '''How do people make chocolate?''',
    '''Why do we get a fever when we are sick?''',
    '''How can different animals perceive different colors?''',
    '''What is natural language processing?''',
    '''What\'s the best way to treat a sunburn?''',
    '''What exactly are vitamins ?''',
    '''How does nuclear energy provide electricity?''',
    '''What\'s the difference between viruses and bacteria?''',
    '''Why are flutes classified as woodwinds when most of them are made out of metal ?''',
    '''Why do people like drinking coffee even though it tastes so bad?''',
    '''What happens when wine ages? How does it make the wine taste better?''',
    '''If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?''',
    '''How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?''',
    '''How does New Zealand have so many large bird predators?''',
]
snake_case_   :   str        =       st.selectbox(
    """What would you like to ask? ---- select <MY QUESTION> to enter a new query""",
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
	snake_case_   :   Optional[Any]        =       st.text_input("""Enter your question here:""", """""")
else:
	snake_case_   :   Dict        =       question_s

if st.button("""Show me!"""):
	if action in [0, 1, 3]:
		if index_type == "mixed":
			snake_case_   :   List[Any]        =       make_support(question, source=wiki_source, method="""dense""", n_results=1_0)
			snake_case_   :   List[str]        =       make_support(question, source=wiki_source, method="""sparse""", n_results=1_0)
			snake_case_   :   int        =       []
			for res_d, res_s in zip(support_list_dense, support_list_sparse):
				if tuple(res_d) not in support_list:
					support_list += [tuple(res_d)]
				if tuple(res_s) not in support_list:
					support_list += [tuple(res_s)]
			snake_case_   :   Union[str, Any]        =       support_list[:1_0]
			snake_case_   :   str        =       '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list])
		else:
			snake_case_   :   int        =       make_support(question, source=wiki_source, method=index_type, n_results=1_0)
	if action in [0, 3]:
		snake_case_   :   Dict        =       answer_question(
		    question_doc,
		    sas_model,
		    sas_tokenizer,
		    min_len=min_len,
		    max_len=int(max_len),
		    sampling=(sampled == """sampled"""),
		    n_beams=n_beams,
		    top_p=top_p,
		    temp=temp,
		)
		st.markdown("""### The model generated answer is:""")
		st.write(answer)
	if action in [0, 1, 3] and wiki_source != "none":
		st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""")
		for i, res in enumerate(support_list):
			snake_case_   :   Tuple        =       '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(""" """, """_"""))
			snake_case_   :   Optional[int]        =       res[1].strip()
			if sec_titles == "":
				snake_case_   :   str        =       '''[{}]({})'''.format(res[0], wiki_url)
			else:
				snake_case_   :   Dict        =       sec_titles.split(""" & """)
				snake_case_   :   int        =       ''' & '''.join(
				    ["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list]
				)
			st.markdown(
			    """{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}""".format(i + 1, res[0], sections),
			    unsafe_allow_html=True,
			)
			if show_passages:
				st.write(
				    """> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True
				)
	if action in [2, 3]:
		snake_case_   :   Tuple        =       find_nearest_training(question)
		snake_case_   :   Optional[Any]        =       nn_train_list[0]
		st.markdown(
		    """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
		)
		snake_case_   :   List[str]        =       [
		    '''{}. {}'''.format(i + 1, """  \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""]))
		    for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""]))
		    if i == 0 or sc > 2
		]
		st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st)))


snake_case_   :   Optional[Any]        =       '''
---

**Disclaimer**

*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
'''




st.sidebar.markdown(disclaimer, unsafe_allow_html=True)





"""simple docstring"""






from typing import Any







class       snake_case__  :







			def __init__(			self			: Union[str, Any]			,  lowercase			: Any  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				data
								UpperCAmelCase			:   Optional[Any]      =				None







			def __repr__(			self			: str  ):





								'''simple docstring'''



								return f"""Node({self.data})"""







class       snake_case__  :







			def __init__(			self			: Optional[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[Any]      =				None







			def __iter__(			self			: Dict  ):





								'''simple docstring'''



								UpperCAmelCase			:   str      =				self.head
								while node:
													yield node.data
													UpperCAmelCase			:   Tuple      =				node.next







			def __len__(			self			: Tuple  ):





								'''simple docstring'''



								return sum(1 for _ in self  )







			def __repr__(			self			: Any  ):





								'''simple docstring'''



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







			def __getitem__(			self			: List[str]			,  lowercase			: int  ):





								'''simple docstring'''



								if not 0 <= index < len(self  ):
													raise ValueError("list index out of range."  )
								for i, node in enumerate(self  ):
													if i == index:
																		return node
								return None







			def __setitem__(			self			: str			,  lowercase			: int			,  lowercase			: Any  ):





								'''simple docstring'''



								if not 0 <= index < len(self  ):
													raise ValueError("list index out of range."  )
								UpperCAmelCase			:   List[str]      =				self.head
								for _ in range(lowercase  ):
													UpperCAmelCase			:   List[Any]      =				current.next
								UpperCAmelCase			:   List[str]      =				data







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: Any  ):





								'''simple docstring'''



								self.insert_nth(len(self  )			,  lowercase  )







			def 			__lowerCAmelCase				(			self			: List[str]			,  lowercase			: Any  ):





								'''simple docstring'''



								self.insert_nth(0			,  lowercase  )







			def 			__lowerCAmelCase				(			self			: List[str]			,  lowercase			: int			,  lowercase			: Any  ):





								'''simple docstring'''



								if not 0 <= index <= len(self  ):
													raise IndexError("list index out of range"  )
								UpperCAmelCase			:   List[Any]      =				Node(lowercase  )
								if self.head is None:
													UpperCAmelCase			:   Optional[Any]      =				new_node
								elif index == 0:
													UpperCAmelCase			:   Optional[int]      =				self.head  # link new_node to head
													UpperCAmelCase			:   Optional[Any]      =				new_node
								else:
													UpperCAmelCase			:   Optional[int]      =				self.head
													for _ in range(index - 1  ):
																		UpperCAmelCase			:   Union[str, Any]      =				temp.next
													UpperCAmelCase			:   Dict      =				temp.next
													UpperCAmelCase			:   Any      =				new_node







			def 			__lowerCAmelCase				(			self			: Dict  ):  # print every node data





								'''simple docstring'''



								print(self  )







			def 			__lowerCAmelCase				(			self			: Optional[Any]  ):





								'''simple docstring'''



								return self.delete_nth(0  )







			def 			__lowerCAmelCase				(			self			: str  ):  # delete from tail





								'''simple docstring'''



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







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: int = 0  ):





								'''simple docstring'''



								if not 0 <= index <= len(self  ) - 1:  # test if index is valid
													raise IndexError("List index out of range."  )
								UpperCAmelCase			:   List[str]      =				self.head  # default first node
								if index == 0:
													UpperCAmelCase			:   Tuple      =				self.head.next
								else:
													UpperCAmelCase			:   Union[str, Any]      =				self.head
													for _ in range(index - 1  ):
																		UpperCAmelCase			:   Dict      =				temp.next
													UpperCAmelCase			:   Optional[Any]      =				temp.next
													UpperCAmelCase			:   int      =				temp.next.next
								return delete_node.data







			def 			__lowerCAmelCase				(			self			: List[Any]  ):





								'''simple docstring'''



								return self.head is None







			def 			__lowerCAmelCase				(			self			: int  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[Any]      =				None
								UpperCAmelCase			:   str      =				self.head

								while current:
													# Store the current node's next node.
													UpperCAmelCase			:   List[Any]      =				current.next
													# Make the current node's next point backwards
													UpperCAmelCase			:   List[str]      =				prev
													# Make the previous node be the current node
													UpperCAmelCase			:   Optional[Any]      =				current
													# Make the current node the next node (to progress iteration)
													UpperCAmelCase			:   Any      =				next_node
								# Return prev in order to put the head at the end
								UpperCAmelCase			:   List[str]      =				prev



def   lowercase_	(    ):




					'''simple docstring'''






					UpperCAmelCase			:   Optional[int]      =				LinkedList()
					assert linked_list.is_empty() is True
					assert str(_lowercase	) == ""

					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(_lowercase	) == i
										linked_list.insert_nth(_lowercase							,      i + 1	)
					assert str(_lowercase	) == "->".join(str(_lowercase	) for i in range(1							,      11	)	)

					linked_list.insert_head(0	)
					linked_list.insert_tail(11	)
					assert str(_lowercase	) == "->".join(str(_lowercase	) for i in range(0							,      12	)	)

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

					assert all(linked_list[i] == i + 1 for i in range(0							,      9	)	) is True

					for i in range(0							,      9	):
										UpperCAmelCase			:   Union[str, Any]      =				-i
					assert all(linked_list[i] == -i for i in range(0							,      9	)	) is True

					linked_list.reverse()
					assert str(_lowercase	) == "->".join(str(_lowercase	) for i in range(-8							,      1	)	)



def   lowercase_	(    ):




					'''simple docstring'''






					UpperCAmelCase			:   Optional[Any]      =				[
					    -9,
					    1_00,
					    Node(77_34_51_12	),
					    "dlrow olleH",
					    7,
					    55_55,
					    0,
					    -1_9_2.5_5_5_5_5,
					    "Hello, world!",
					    7_7.9,
					    Node(10	),
					    None,
					    None,
					    1_2.2_0,
					]
					UpperCAmelCase			:   Optional[Any]      =				LinkedList()

					for i in test_input:
										linked_list.insert_tail(_lowercase	)

					# Check if it's empty or not
					assert linked_list.is_empty() is False
					assert (
					    str(_lowercase	) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
					    "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
					)

					# Delete the head
					UpperCAmelCase			:   Tuple      =				linked_list.delete_head()
					assert result == -9
					assert (
					    str(_lowercase	) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
					    "Hello, world!->77.9->Node(10)->None->None->12.2"
					)

					# Delete the tail
					UpperCAmelCase			:   Any      =				linked_list.delete_tail()
					assert result == 1_2.2
					assert (
					    str(_lowercase	) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
					    "Hello, world!->77.9->Node(10)->None->None"
					)

					# Delete a node in specific location in linked list
					UpperCAmelCase			:   Union[str, Any]      =				linked_list.delete_nth(10	)
					assert result is None
					assert (
					    str(_lowercase	) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
					    "Hello, world!->77.9->Node(10)->None"
					)

					# Add a Node instance to its head
					linked_list.insert_head(Node("Hello again, world!"	)	)
					assert (
					    str(_lowercase	)
					    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
					    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
					)

					# Add None to its tail
					linked_list.insert_tail(_lowercase	)
					assert (
					    str(_lowercase	)
					    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
					    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
					)

					# Reverse the linked list
					linked_list.reverse()
					assert (
					    str(_lowercase	)
					    == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
					    "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
					)



def   lowercase_	(    ):




					'''simple docstring'''






					from doctest import testmod

					testmod()

					UpperCAmelCase			:   Any      =				LinkedList()
					linked_list.insert_head(input("Inserting 1st at head "	).strip()	)
					linked_list.insert_head(input("Inserting 2nd at head "	).strip()	)
					print("\nPrint list:"	)
					linked_list.print_list()
					linked_list.insert_tail(input("\nInserting 1st at tail "	).strip()	)
					linked_list.insert_tail(input("Inserting 2nd at tail "	).strip()	)
					print("\nPrint list:"	)
					linked_list.print_list()
					print("\nDelete head"	)
					linked_list.delete_head()
					print("Delete tail"	)
					linked_list.delete_tail()
					print("\nPrint list:"	)
					linked_list.print_list()
					print("\nReverse linked list"	)
					linked_list.reverse()
					print("\nPrint list:"	)
					linked_list.print_list()
					print("\nString representation of linked list:"	)
					print(_lowercase	)
					print("\nReading/changing Node data using indexing:"	)
					print(F"""Element at Position 1: {linked_list[1]}"""	)
					UpperCAmelCase			:   int      =				input("Enter New Value: "	).strip()
					print("New list:"	)
					print(_lowercase	)
					print(F"""length of linked_list is : {len(_lowercase	)}"""	)


if __name__ == "__main__":
	main()


