




"""simple docstring"""




import os

import jsonlines
import numpy as np
from tqdm import tqdm


lowerCAmelCase				:     List[str]					=				2048
lowerCAmelCase				:     Any					=				4096
lowerCAmelCase				:     int					=				42
lowerCAmelCase				:     Optional[Any]					=				os.environ.pop("""PROCESS_TRAIN""", """false""")
lowerCAmelCase				:     Tuple					=				{"""null""": 0, """short""": 1, """long""": 2, """yes""": 3, """no""": 4}



def        a__					(							snake_case__							)		->   Any:
			def choose_first(snake_case__			,					snake_case__=False							):
						assert isinstance(snake_case__			,					snake_case__							)
						if len(snake_case__							) == 1:
									lowerCamelCase      =   answer[0]
									return {k: [answer[k]] for k in answer} if is_long_answer else answer
						for a in answer:
									if is_long_answer:
												lowerCamelCase      =   {k: [a[k]] for k in a}
									if len(a["""start_token"""]							) > 0:
												break
						return a

			lowerCamelCase      =   {"""id""": example["""id"""]}
			lowerCamelCase      =   example["""annotations"""]
			lowerCamelCase      =   annotation["""yes_no_answer"""]
			if 0 in yes_no_answer or 1 in yes_no_answer:
						lowerCamelCase      =   ["""yes"""] if 1 in yes_no_answer else ["""no"""]
						lowerCamelCase      =   lowerCamelCase      =   []
						lowerCamelCase      =   lowerCamelCase      =   []
						lowerCamelCase      =   ["""<cls>"""]
			else:
						lowerCamelCase      =   ["""short"""]
						lowerCamelCase      =   choose_first(annotation["""short_answers"""]							)
						if len(out["""start_token"""]							) == 0:
									# answer will be long if short is not available
									lowerCamelCase      =   ["""long"""]
									lowerCamelCase      =   choose_first(annotation["""long_answer"""]			,					is_long_answer=snake_case__							)
									lowerCamelCase      =   []
						answer.update(snake_case__							)

			# disregard some samples
			if len(answer["""start_token"""]							) > 1 or answer["start_token"] == answer["end_token"]:
						lowerCamelCase      =   True
			else:
						lowerCamelCase      =   False

			lowerCamelCase      =   ["""start_token""", """end_token""", """start_byte""", """end_byte""", """text"""]
			if not all(isinstance(answer[k]			,					snake_case__							) for k in cols							):
						raise ValueError("""Issue in ID"""			,					example["""id"""]							)

			return answer



def        a__					(							snake_case__			,					snake_case__=False							)		->   Tuple:
			lowerCamelCase      =   _get_single_answer(snake_case__							)
			# bytes are of no use
			del answer["start_byte"]
			del answer["end_byte"]

			# handle yes_no answers explicitly
			if answer["category"][0] in ["yes", "no"]:  # category is list with one element
						lowerCamelCase      =   example["""document"""]["""tokens"""]
						lowerCamelCase      =   []
						for i in range(len(doc["""token"""]							)							):
									if not doc["is_html"][i]:
												context.append(doc["""token"""][i]							)
						return {
						    "context": " ".join(snake_case__							),
						    "answer": {
						        "start_token": -1_00,  # ignore index in cross-entropy
						        "end_token": -1_00,  # ignore index in cross-entropy
						        "category": answer["category"],
						        "span": answer["category"],  # extra
						    },
						}

			# later, help in removing all no answers
			if answer["start_token"] == [-1]:
						return {
						    "context": "None",
						    "answer": {
						        "start_token": -1,
						        "end_token": -1,
						        "category": "null",
						        "span": "None",  # extra
						    },
						}

			# handling normal samples

			lowerCamelCase      =   ["""start_token""", """end_token"""]
			answer.update({k: answer[k][0] if len(answer[k]							) > 0 else answer[k] for k in cols}							)  # e.g. [10] == 10

			lowerCamelCase      =   example["""document"""]["""tokens"""]
			lowerCamelCase      =   answer["""start_token"""]
			lowerCamelCase      =   answer["""end_token"""]

			lowerCamelCase      =   []
			for i in range(len(doc["""token"""]							)							):
						if not doc["is_html"][i]:
									context.append(doc["""token"""][i]							)
						else:
									if answer["start_token"] > i:
												start_token -= 1
									if answer["end_token"] > i:
												end_token -= 1
			lowerCamelCase      =   """ """.join(context[start_token:end_token]							)

			# checking above code
			if assertion:
						lowerCamelCase      =   doc["""is_html"""][answer["""start_token"""] : answer["""end_token"""]]
						lowerCamelCase      =   doc["""token"""][answer["""start_token"""] : answer["""end_token"""]]
						lowerCamelCase      =   """ """.join([old[i] for i in range(len(snake_case__							)							) if not is_html[i]]							)
						if new != old:
									print("""ID:"""			,					example["""id"""]							)
									print("""New:"""			,					snake_case__			,					end="""\n"""							)
									print("""Old:"""			,					snake_case__			,					end="""\n\n"""							)

			return {
			    "context": " ".join(snake_case__							),
			    "answer": {
			        "start_token": start_token,
			        "end_token": end_token - 1,  # this makes it inclusive
			        "category": answer["category"],  # either long or short
			        "span": new,  # extra
			    },
			}



def        a__					(							snake_case__			,					snake_case__			,					snake_case__=20_48			,					snake_case__=40_96			,					snake_case__=True							)		->   Any:
			# overlap will be of doc_stride - q_len

			lowerCamelCase      =   get_context_and_ans(snake_case__			,					assertion=snake_case__							)
			lowerCamelCase      =   out["""answer"""]

			# later, removing these samples
			if answer["start_token"] == -1:
						return {
						    "example_id": example["id"],
						    "input_ids": [[-1]],
						    "labels": {
						        "start_token": [-1],
						        "end_token": [-1],
						        "category": ["null"],
						    },
						}

			lowerCamelCase      =   tokenizer(example["""question"""]["""text"""]			,					out["""context"""]							).input_ids
			lowerCamelCase      =   input_ids.index(tokenizer.sep_token_id							) + 1

			# return yes/no
			if answer["category"][0] in ["yes", "no"]:  # category is list with one element
						lowerCamelCase      =   []
						lowerCamelCase      =   []
						lowerCamelCase      =   input_ids[:q_len]
						lowerCamelCase      =   range(snake_case__			,					len(snake_case__							)			,					max_length - doc_stride							)
						for i in doc_start_indices:
									lowerCamelCase      =   i + max_length - q_len
									lowerCamelCase      =   input_ids[i:end_index]
									inputs.append(q_indices + slice							)
									category.append(answer["""category"""][0]							)
									if slice[-1] == tokenizer.sep_token_id:
												break

						return {
						    "example_id": example["id"],
						    "input_ids": inputs,
						    "labels": {
						        "start_token": [-1_00] * len(snake_case__							),
						        "end_token": [-1_00] * len(snake_case__							),
						        "category": category,
						    },
						}

			lowerCamelCase      =   out["""context"""].split()
			lowerCamelCase      =   splitted_context[answer["""end_token"""]]
			lowerCamelCase      =   len(
			    tokenizer(
			        """ """.join(splitted_context[: answer["""start_token"""]]							)			,					add_special_tokens=snake_case__			,					).input_ids							)
			lowerCamelCase      =   len(
			    tokenizer(""" """.join(splitted_context[: answer["""end_token"""]]							)			,					add_special_tokens=snake_case__							).input_ids							)

			answer["start_token"] += q_len
			answer["end_token"] += q_len

			# fixing end token
			lowerCamelCase      =   len(tokenizer(snake_case__			,					add_special_tokens=snake_case__							).input_ids							)
			if num_sub_tokens > 1:
						answer["end_token"] += num_sub_tokens - 1

			lowerCamelCase      =   input_ids[answer["""start_token"""] : answer["""end_token"""] + 1]  # right & left are inclusive
			lowerCamelCase      =   answer["""start_token"""]
			lowerCamelCase      =   answer["""end_token"""]

			if assertion:
						lowerCamelCase      =   tokenizer.decode(snake_case__							)
						if answer["span"] != new:
									print("""ISSUE IN TOKENIZATION"""							)
									print("""OLD:"""			,					answer["""span"""]							)
									print("""NEW:"""			,					snake_case__			,					end="""\n\n"""							)

			if len(snake_case__							) <= max_length:
						return {
						    "example_id": example["id"],
						    "input_ids": [input_ids],
						    "labels": {
						        "start_token": [answer["start_token"]],
						        "end_token": [answer["end_token"]],
						        "category": answer["category"],
						    },
						}

			lowerCamelCase      =   input_ids[:q_len]
			lowerCamelCase      =   range(snake_case__			,					len(snake_case__							)			,					max_length - doc_stride							)

			lowerCamelCase      =   []
			lowerCamelCase      =   []
			lowerCamelCase      =   []
			lowerCamelCase      =   []  # null, yes, no, long, short
			for i in doc_start_indices:
						lowerCamelCase      =   i + max_length - q_len
						lowerCamelCase      =   input_ids[i:end_index]
						inputs.append(q_indices + slice							)
						assert len(inputs[-1]							) <= max_length, "Issue in truncating length"

						if start_token >= i and end_token <= end_index - 1:
									lowerCamelCase      =   start_token - i + q_len
									lowerCamelCase      =   end_token - i + q_len
									answers_category.append(answer["""category"""][0]							)  # ["short"] -> "short"
						else:
									lowerCamelCase      =   -1_00
									lowerCamelCase      =   -1_00
									answers_category.append("""null"""							)
						lowerCamelCase      =   inputs[-1][start_token : end_token + 1]

						answers_start_token.append(snake_case__							)
						answers_end_token.append(snake_case__							)
						if assertion:
									if new != old and new != [tokenizer.cls_token_id]:
												print("""ISSUE in strided for ID:"""			,					example["""id"""]							)
												print("""New:"""			,					tokenizer.decode(snake_case__							)							)
												print("""Old:"""			,					tokenizer.decode(snake_case__							)			,					end="""\n\n"""							)
						if slice[-1] == tokenizer.sep_token_id:
									break

			return {
			    "example_id": example["id"],
			    "input_ids": inputs,
			    "labels": {
			        "start_token": answers_start_token,
			        "end_token": answers_end_token,
			        "category": answers_category,
			    },
			}



def        a__					(							snake_case__			,					snake_case__			,					snake_case__=20_48			,					snake_case__=40_96			,					snake_case__=False							)		->   str:
			lowerCamelCase      =   get_strided_contexts_and_ans(
			    snake_case__			,					snake_case__			,					doc_stride=snake_case__			,					max_length=snake_case__			,					assertion=snake_case__			,					)

			return example



def        a__					(							snake_case__			,					snake_case__							)		->   Tuple:
			with jsonlines.open(snake_case__			,					"""a"""							) as writer:
						for example in tqdm(snake_case__			,					total=len(snake_case__							)			,					desc="""Saving samples ... """							):
									lowerCamelCase      =   example["""labels"""]
									for ids, start, end, cat in zip(
									    example["""input_ids"""]			,					labels["""start_token"""]			,					labels["""end_token"""]			,					labels["""category"""]			,					):
												if start == -1 and end == -1:
															continue  # leave waste samples with no answer
												if cat == "null" and np.random.rand() < 0.6:
															continue  # removing 50 % samples
												writer.write(
												    {
												        """input_ids""": ids,
												        """start_token""": start,
												        """end_token""": end,
												        """category""": CATEGORY_MAPPING[cat],
												    }							)


if __name__ == "__main__":
					from datasets import load_dataset

					from transformers import BigBirdTokenizer

					lowerCAmelCase				:     Optional[int]					=				load_dataset("""natural_questions""")
					lowerCAmelCase				:     Optional[Any]					=				BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""")

					lowerCAmelCase				:     Dict					=				data["""train""" if PROCESS_TRAIN == """true""" else """validation"""]

					lowerCAmelCase				:     int					=				{
					    """tokenizer""": tokenizer,
					    """doc_stride""": DOC_STRIDE,
					    """max_length""": MAX_LENGTH,
					    """assertion""": False,
					}
					lowerCAmelCase				:     Optional[Any]					=				data.map(prepare_inputs, fn_kwargs=fn_kwargs)
					lowerCAmelCase				:     Dict					=				data.remove_columns(["""annotations""", """document""", """id""", """question"""])
					print(data)

					np.random.seed(SEED)
					lowerCAmelCase				:     List[str]					=				"""nq-training.jsonl""" if PROCESS_TRAIN == """true""" else """nq-validation.jsonl"""
					save_to_disk(data, file_name=cache_file_name)









"""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


lowerCAmelCase				:     int					=				"""bart"""
lowerCAmelCase				:     List[Any]					=				True



@st.cache(allow_output_mutation=snake_case__							)
def        a__					(							)		->   List[Any]:
			if LOAD_DENSE_INDEX:
						lowerCamelCase      =   AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased"""							)
						lowerCamelCase      =   AutoModel.from_pretrained("""yjernite/retribert-base-uncased"""							).to("""cuda:0"""							)
						lowerCamelCase      =   qar_model.eval()
			else:
						lowerCamelCase ,  lowerCamelCase      =   (None, None)
			if MODEL_TYPE == "bart":
						lowerCamelCase      =   AutoTokenizer.from_pretrained("""yjernite/bart_eli5"""							)
						lowerCamelCase      =   AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5"""							).to("""cuda:0"""							)
						lowerCamelCase      =   torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth"""							)
						sas_model.load_state_dict(save_dict["""model"""]							)
						lowerCamelCase      =   sas_model.eval()
			else:
						lowerCamelCase ,  lowerCamelCase      =   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=snake_case__							)
def        a__					(							)		->   List[str]:
			if LOAD_DENSE_INDEX:
						lowerCamelCase      =   faiss.StandardGpuResources()
						lowerCamelCase      =   datasets.load_dataset(path="""wiki_snippets"""			,					name="""wiki40b_en_100_0"""							)["""train"""]
						lowerCamelCase      =   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)			,					)
						lowerCamelCase      =   faiss.IndexFlatIP(1_28							)
						lowerCamelCase      =   faiss.index_cpu_to_gpu(snake_case__			,					1			,					snake_case__							)
						wikiaab_gpu_index_flat.add(snake_case__							)  # TODO fix for larger GPU
			else:
						lowerCamelCase ,  lowerCamelCase      =   (None, None)
			lowerCamelCase      =   Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}]							)
			return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)



@st.cache(allow_output_mutation=snake_case__							)
def        a__					(							)		->   Any:
			lowerCamelCase      =   datasets.load_dataset("""eli5"""			,					name="""LFQA_reddit"""							)
			lowerCamelCase      =   elia["""train_eli5"""]
			lowerCamelCase      =   np.memmap(
			    """eli5_questions_reps.dat"""			,					dtype="""float32"""			,					mode="""r"""			,					shape=(elia_train.num_rows, 1_28)							)
			lowerCamelCase      =   faiss.IndexFlatIP(1_28							)
			eli5_train_q_index.add(snake_case__							)
			return (elia_train, eli5_train_q_index)


lowerCAmelCase				,		lowerCAmelCase				,		lowerCAmelCase				:     Any					=				load_indexes()
lowerCAmelCase				,		lowerCAmelCase				,		lowerCAmelCase				,		lowerCAmelCase				:     List[Any]					=				load_models()
lowerCAmelCase				,		lowerCAmelCase				:     int					=				load_train_data()



def        a__					(							snake_case__			,					snake_case__=10							)		->   Tuple:
			lowerCamelCase      =   embed_questions_for_retrieval([question]			,					snake_case__			,					snake_case__							)
			lowerCamelCase ,  lowerCamelCase      =   eli5_train_q_index.search(snake_case__			,					snake_case__							)
			lowerCamelCase      =   [elia_train[int(snake_case__							)] for i in I[0]]
			return nn_examples



def        a__					(							snake_case__			,					snake_case__="wiki40b"			,					snake_case__="dense"			,					snake_case__=10							)		->   Dict:
			if source == "none":
						lowerCamelCase ,  lowerCamelCase      =   (""" <P> """.join(["""""" for _ in range(11							)]							).strip(), [])
			else:
						if method == "dense":
									lowerCamelCase ,  lowerCamelCase      =   query_qa_dense_index(
									    snake_case__			,					snake_case__			,					snake_case__			,					snake_case__			,					snake_case__			,					snake_case__							)
						else:
									lowerCamelCase ,  lowerCamelCase      =   query_es_index(
									    snake_case__			,					snake_case__			,					index_name="""english_wiki40b_snippets_100w"""			,					n_results=snake_case__			,					)
			lowerCamelCase      =   [
			    (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst
			]
			lowerCamelCase      =   """question: {} context: {}""".format(snake_case__			,					snake_case__							)
			return question_doc, support_list



@st.cache(
    hash_funcs={
        torch.Tensor: (lambda snake_case__							: None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda snake_case__							: None),
    }							)
def        a__					(							snake_case__			,					snake_case__			,					snake_case__			,					snake_case__=64			,					snake_case__=2_56			,					snake_case__=False			,					snake_case__=2			,					snake_case__=0.95			,					snake_case__=0.8							)		->   str:
			with torch.no_grad():
						lowerCamelCase      =   qa_sas_generate(
						    snake_case__			,					snake_case__			,					snake_case__			,					num_answers=1			,					num_beams=snake_case__			,					min_len=snake_case__			,					max_len=snake_case__			,					do_sample=snake_case__			,					temp=snake_case__			,					top_p=snake_case__			,					top_k=snake_case__			,					max_input_length=10_24			,					device="""cuda:0"""			,					)[0]
			return (answer, support_list)


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

# Start sidebar
lowerCAmelCase				:     Tuple					=				"""<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"""
lowerCAmelCase				:     Optional[int]					=				"""
<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
lowerCAmelCase				:     Union[str, Any]					=				"""
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)

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

lowerCAmelCase				:     List[str]					=				st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
					lowerCAmelCase				:     List[str]					=				"""
    ### 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)
					lowerCAmelCase				:     str					=				st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
					lowerCAmelCase				:     Optional[Any]					=				st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
					lowerCAmelCase				:     Optional[int]					=				"""wiki40b"""
					lowerCAmelCase				:     List[str]					=				"""dense"""

lowerCAmelCase				:     Tuple					=				"""beam"""
lowerCAmelCase				:     Optional[int]					=				2
lowerCAmelCase				:     Dict					=				64
lowerCAmelCase				:     Optional[int]					=				256
lowerCAmelCase				:     Union[str, Any]					=				None
lowerCAmelCase				:     Optional[int]					=				None
lowerCAmelCase				:     Tuple					=				st.sidebar.checkbox("""Generation options""")
if generate_options:
					lowerCAmelCase				:     Optional[Any]					=				"""
    ### 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)
					lowerCAmelCase				:     str					=				st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
					lowerCAmelCase				:     int					=				st.sidebar.slider(
					    """Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None
					)
					lowerCAmelCase				:     Tuple					=				st.sidebar.slider(
					    """Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None
					)
					if sampled == "beam":
										lowerCAmelCase				:     int					=				st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
					else:
										lowerCAmelCase				:     str					=				st.sidebar.slider(
										    """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None
										)
										lowerCAmelCase				:     int					=				st.sidebar.slider(
										    """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None
										)
										lowerCAmelCase				:     List[Any]					=				None

# start main text
lowerCAmelCase				:     Optional[int]					=				[
    """<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?""",
]
lowerCAmelCase				:     List[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>":
					lowerCAmelCase				:     Any					=				st.text_input("""Enter your question here:""", """""")
else:
					lowerCAmelCase				:     List[str]					=				question_s

if st.button("""Show me!"""):
					if action in [0, 1, 3]:
										if index_type == "mixed":
															lowerCAmelCase				,		lowerCAmelCase				:     Any					=				make_support(question, source=wiki_source, method="""dense""", n_results=10)
															lowerCAmelCase				,		lowerCAmelCase				:     Tuple					=				make_support(question, source=wiki_source, method="""sparse""", n_results=10)
															lowerCAmelCase				:     Union[str, Any]					=				[]
															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)]
															lowerCAmelCase				:     int					=				support_list[:10]
															lowerCAmelCase				:     str					=				"""<P> """ + """ <P> """.join([res[-1] for res in support_list])
										else:
															lowerCAmelCase				,		lowerCAmelCase				:     Optional[Any]					=				make_support(question, source=wiki_source, method=index_type, n_results=10)
					if action in [0, 3]:
										lowerCAmelCase				,		lowerCAmelCase				:     int					=				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):
															lowerCAmelCase				:     Any					=				"""https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_"""))
															lowerCAmelCase				:     Dict					=				res[1].strip()
															if sec_titles == "":
																				lowerCAmelCase				:     Optional[Any]					=				"""[{}]({})""".format(res[0], wiki_url)
															else:
																				lowerCAmelCase				:     Tuple					=				sec_titles.split(""" & """)
																				lowerCAmelCase				:     List[str]					=				""" & """.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]:
										lowerCAmelCase				:     Tuple					=				find_nearest_training(question)
										lowerCAmelCase				:     List[str]					=				nn_train_list[0]
										st.markdown(
										    """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
										)
										lowerCAmelCase				:     int					=				[
										    """{}. {}""".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)))


lowerCAmelCase				:     Tuple					=				"""
---

**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)



