





import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
      import tensorflow as tf

if is_torch_available():
      import torch


_UpperCAmelCase             =							logging.get_logger(__name__)






class        snake_case_    :






  def __init__(							self			:					Optional[Any]       ,  _snake_case			:					str = None       ,  _snake_case			:					uuid.UUID = None       ,  _snake_case			:					List[str]=None       ,  _snake_case			:					Tuple=None      )->Optional[Any]:






   '''simple docstring'''

   if not conversation_id:
    __lowerCAmelCase					:	Any      =       uuid.uuida()
   if past_user_inputs is None:
    __lowerCAmelCase					:	Optional[Any]      =       []
   if generated_responses is None:
    __lowerCAmelCase					:	Optional[Any]      =       []

   __lowerCAmelCase					:	uuid.UUID      =       conversation_id
   __lowerCAmelCase					:	List[str]      =       past_user_inputs
   __lowerCAmelCase					:	List[str]      =       generated_responses
   __lowerCAmelCase					:	Optional[str]      =       text






  def __eq__(							self			:					str       ,  _snake_case			:					Dict      )->Optional[Any]:






   '''simple docstring'''

   if not isinstance(_snake_case       ,  _snake_case      ):
    return False
   if self.uuid == other.uuid:
    return True
   return (
       self.new_user_input == other.new_user_input
       and self.past_user_inputs == other.past_user_inputs
       and self.generated_responses == other.generated_responses
   )






  def 				UpperCAmelCase__						(							self			:					Optional[Any]       ,  _snake_case			:					str       ,  _snake_case			:					bool = False      )->Any:






   '''simple docstring'''

   if self.new_user_input:
    if overwrite:
     logger.warning(
         F'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '''
         F'''with: "{text}".'''      )
     __lowerCAmelCase					:	int      =       text
    else:
     logger.warning(
         F'''User input added while unprocessed input was existing: "{self.new_user_input}" new input '''
         F'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input'''      )
   else:
    __lowerCAmelCase					:	List[str]      =       text






  def 				UpperCAmelCase__						(							self			:					List[str]      )->int:






   '''simple docstring'''

   if self.new_user_input:
    self.past_user_inputs.append(self.new_user_input      )
   __lowerCAmelCase					:	List[str]      =       None






  def 				UpperCAmelCase__						(							self			:					List[str]       ,  _snake_case			:					str      )->List[str]:






   '''simple docstring'''

   self.generated_responses.append(_snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->Optional[Any]:






   '''simple docstring'''

   for user_input, generated_response in zip(self.past_user_inputs       ,  self.generated_responses      ):
    yield True, user_input
    yield False, generated_response
   if self.new_user_input:
    yield True, self.new_user_input






  def __repr__(							self			:					Dict      )->Optional[int]:






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       F'''Conversation id: {self.uuid} \n'''
   for is_user, text in self.iter_texts():
    __lowerCAmelCase					:	str      =       """user""" if is_user else """bot"""
    output += F'''{name} >> {text} \n'''
   return output






@add_end_docstrings(
    __lowercase					,R'\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    '					,)
class        snake_case_    (		__lowercase						):






  def __init__(							self			:					List[Any]       ,  *_snake_case			:					str       ,  **_snake_case			:					List[Any]      )->List[Any]:






   '''simple docstring'''

   super().__init__(*_snake_case       ,  **_snake_case      )
   if self.tokenizer.pad_token_id is None:
    __lowerCAmelCase					:	Optional[int]      =       self.tokenizer.eos_token






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					Any=None       ,  _snake_case			:					str=None       ,  _snake_case			:					Tuple=None       ,  **_snake_case			:					str      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       {}
   __lowerCAmelCase					:	Tuple      =       {}
   __lowerCAmelCase					:	List[str]      =       {}

   if min_length_for_response is not None:
    __lowerCAmelCase					:	Optional[int]      =       min_length_for_response
   if minimum_tokens is not None:
    __lowerCAmelCase					:	Tuple      =       minimum_tokens

   if "max_length" in generate_kwargs:
    __lowerCAmelCase					:	List[str]      =       generate_kwargs["""max_length"""]
    # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
   if clean_up_tokenization_spaces is not None:
    __lowerCAmelCase					:	int      =       clean_up_tokenization_spaces

   if generate_kwargs:
    forward_params.update(_snake_case      )
   return preprocess_params, forward_params, postprocess_params






  def __call__(							self			:					int       ,  _snake_case			:					Union[Conversation, List[Conversation]]       ,  _snake_case			:					List[str]=0       ,  **_snake_case			:					Optional[Any]      )->Optional[int]:






   '''simple docstring'''

   __lowerCAmelCase					:	Union[str, Any]      =       super().__call__(_snake_case       ,  num_workers=_snake_case       ,  **_snake_case      )
   if isinstance(_snake_case       ,  _snake_case      ) and len(_snake_case      ) == 1:
    return outputs[0]
   return outputs






  def 				UpperCAmelCase__						(							self			:					str       ,  _snake_case			:					Conversation       ,  _snake_case			:					Tuple=32      )->Dict[str, Any]:






   '''simple docstring'''

   if not isinstance(_snake_case       ,  _snake_case      ):
    raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""      )
   if conversation.new_user_input is None:
    raise ValueError(
        F'''Conversation with UUID {type(conversation.uuid      )} does not contain new user input to process. '''
        """Add user inputs with the conversation's `add_user_input` method"""      )
   if hasattr(self.tokenizer       ,  """_build_conversation_input_ids"""      ):
    __lowerCAmelCase					:	str      =       self.tokenizer._build_conversation_input_ids(_snake_case      )
   else:
    # If the tokenizer cannot handle conversations, we default to only the old version
    __lowerCAmelCase					:	Tuple      =       self._legacy_parse_and_tokenize(_snake_case      )

   if self.framework == "pt":
    __lowerCAmelCase					:	int      =       torch.LongTensor([input_ids]      )
   elif self.framework == "tf":
    __lowerCAmelCase					:	Dict      =       tf.constant([input_ids]      )
   return {"input_ids": input_ids, "conversation": conversation}






  def 				UpperCAmelCase__						(							self			:					List[Any]       ,  _snake_case			:					List[str]       ,  _snake_case			:					Optional[int]=10       ,  **_snake_case			:					int      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       generate_kwargs.get("""max_length"""       ,  self.model.config.max_length      )

   __lowerCAmelCase					:	Tuple      =       model_inputs["""input_ids"""].shape[1]
   if max_length - minimum_tokens < n:
    logger.warning(F'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})'''      )
    __lowerCAmelCase					:	Dict      =       max_length - minimum_tokens
    __lowerCAmelCase					:	Dict      =       model_inputs["""input_ids"""][:, -trim:]
    if "attention_mask" in model_inputs:
     __lowerCAmelCase					:	List[str]      =       model_inputs["""attention_mask"""][:, -trim:]
   __lowerCAmelCase					:	Union[str, Any]      =       model_inputs.pop("""conversation"""      )
   __lowerCAmelCase					:	Any      =       max_length
   __lowerCAmelCase					:	Union[str, Any]      =       self.model.generate(**_snake_case       ,  **_snake_case      )
   if self.model.config.is_encoder_decoder:
    __lowerCAmelCase					:	str      =       1
   else:
    __lowerCAmelCase					:	Optional[int]      =       n
   return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






  def 				UpperCAmelCase__						(							self			:					str       ,  _snake_case			:					Any       ,  _snake_case			:					Optional[Any]=True      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       model_outputs["""output_ids"""]
   __lowerCAmelCase					:	str      =       self.tokenizer.decode(
       output_ids[0]       ,  skip_special_tokens=_snake_case       ,  clean_up_tokenization_spaces=_snake_case       ,  )
   __lowerCAmelCase					:	Union[str, Any]      =       model_outputs["""conversation"""]
   conversation.mark_processed()
   conversation.append_response(_snake_case      )
   return conversation






  def 				UpperCAmelCase__						(							self			:					Union[str, Any]       ,  _snake_case			:					Conversation      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       self.tokenizer.eos_token_id
   __lowerCAmelCase					:	Tuple      =       []
   for is_user, text in conversation.iter_texts():
    if eos_token_id is not None:
     input_ids.extend(self.tokenizer.encode(_snake_case       ,  add_special_tokens=_snake_case      ) + [eos_token_id]      )
    else:
     input_ids.extend(self.tokenizer.encode(_snake_case       ,  add_special_tokens=_snake_case      )      )

   if len(_snake_case      ) > self.tokenizer.model_max_length:
    __lowerCAmelCase					:	Optional[Any]      =       input_ids[-self.tokenizer.model_max_length :]
   return input_ids






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


_UpperCAmelCase             =							'bart'
_UpperCAmelCase             =							True






@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   List[Any]:
 if LOAD_DENSE_INDEX:
  __lowerCAmelCase					:	Dict      =       AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased"""   )
  __lowerCAmelCase					:	str      =       AutoModel.from_pretrained("""yjernite/retribert-base-uncased"""   ).to("""cuda:0"""   )
  __lowerCAmelCase					:	Tuple      =       qar_model.eval()
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	str      =       (None, None)
 if MODEL_TYPE == "bart":
  __lowerCAmelCase					:	Optional[Any]      =       AutoTokenizer.from_pretrained("""yjernite/bart_eli5"""   )
  __lowerCAmelCase					:	str      =       AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5"""   ).to("""cuda:0"""   )
  __lowerCAmelCase					:	str      =       torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth"""   )
  sas_model.load_state_dict(save_dict["""model"""]   )
  __lowerCAmelCase					:	List[str]      =       sas_model.eval()
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[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=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   Tuple:
 if LOAD_DENSE_INDEX:
  __lowerCAmelCase					:	List[str]      =       faiss.StandardGpuResources()
  __lowerCAmelCase					:	Optional[int]      =       datasets.load_dataset(path="""wiki_snippets"""   ,   name="""wiki40b_en_100_0"""   )["""train"""]
  __lowerCAmelCase					:	Optional[int]      =       np.memmap(
      """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"""   ,   dtype="""float32"""   ,   mode="""r"""   ,   shape=(wikiaab_passages.num_rows, 128)   ,   )
  __lowerCAmelCase					:	int      =       faiss.IndexFlatIP(128   )
  __lowerCAmelCase					:	Optional[int]      =       faiss.index_cpu_to_gpu(SCREAMING_SNAKE_CASE   ,   1   ,   SCREAMING_SNAKE_CASE   )
  wikiaab_gpu_index_flat.add(SCREAMING_SNAKE_CASE   )  # TODO fix for larger GPU
 else:
  __lowerCAmelCase ,					__lowerCAmelCase					:	Dict      =       (None, None)
 __lowerCAmelCase					:	List[Any]      =       Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}]   )
 return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)






@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE   )
def 	_SCREAMING_SNAKE_CASE		(      )      ->   Optional[Any]:
 __lowerCAmelCase					:	Tuple      =       datasets.load_dataset("""eli5"""   ,   name="""LFQA_reddit"""   )
 __lowerCAmelCase					:	int      =       elia["""train_eli5"""]
 __lowerCAmelCase					:	int      =       np.memmap(
     """eli5_questions_reps.dat"""   ,   dtype="""float32"""   ,   mode="""r"""   ,   shape=(elia_train.num_rows, 128)   )
 __lowerCAmelCase					:	List[Any]      =       faiss.IndexFlatIP(128   )
 eli5_train_q_index.add(SCREAMING_SNAKE_CASE   )
 return (elia_train, eli5_train_q_index)


_UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase             =							load_indexes()
_UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase       ,     _UpperCAmelCase             =							load_models()
_UpperCAmelCase       ,     _UpperCAmelCase             =							load_train_data()






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:List[Any]   ,   SCREAMING_SNAKE_CASE		:List[str]=10   )      ->   List[str]:
 __lowerCAmelCase					:	Optional[Any]      =       embed_questions_for_retrieval([question]   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase ,					__lowerCAmelCase					:	Dict      =       eli5_train_q_index.search(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
 __lowerCAmelCase					:	str      =       [elia_train[int(SCREAMING_SNAKE_CASE   )] for i in I[0]]
 return nn_examples






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






@st.cache(
    hash_funcs={
        torch.Tensor: (lambda SCREAMING_SNAKE_CASE   : None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda SCREAMING_SNAKE_CASE   : None),
    }   )
def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Optional[int]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:Dict   ,   SCREAMING_SNAKE_CASE		:int=64   ,   SCREAMING_SNAKE_CASE		:int=256   ,   SCREAMING_SNAKE_CASE		:Tuple=False   ,   SCREAMING_SNAKE_CASE		:Union[str, Any]=2   ,   SCREAMING_SNAKE_CASE		:int=0.95   ,   SCREAMING_SNAKE_CASE		:Any=0.8   )      ->   str:
 with torch.no_grad():
  __lowerCAmelCase					:	Any      =       qa_sas_generate(
      SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   num_answers=1   ,   num_beams=SCREAMING_SNAKE_CASE   ,   min_len=SCREAMING_SNAKE_CASE   ,   max_len=SCREAMING_SNAKE_CASE   ,   do_sample=SCREAMING_SNAKE_CASE   ,   temp=SCREAMING_SNAKE_CASE   ,   top_p=SCREAMING_SNAKE_CASE   ,   top_k=SCREAMING_SNAKE_CASE   ,   max_input_length=1_024   ,   device="""cuda:0"""   ,   )[0]
 return (answer, support_list)


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

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

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

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

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

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

# start main text
_UpperCAmelCase             =							[
    '<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?',
]
_UpperCAmelCase             =							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>":
      _UpperCAmelCase             =							st.text_input('Enter your question here:', '')
else:
      _UpperCAmelCase             =							question_s

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


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







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