




import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference





class     lowerCamelCase__(					__lowerCamelCase ,     unittest.TestCase):
      UpperCAmelCase__      :	Tuple    		=   ShapEImgaImgPipeline
      UpperCAmelCase__      :	Optional[Any]    		=   ['image']
      UpperCAmelCase__      :	int    		=   ['image']
      UpperCAmelCase__      :	Any    		=   [
          'num_images_per_prompt',
          'num_inference_steps',
          'generator',
          'latents',
          'guidance_scale',
          'frame_size',
          'output_type',
          'return_dict',
      ]
      UpperCAmelCase__      :	int    		=   False
      @property
      def 			lowerCAmelCase__						(				self: int   ):
             return 32
      @property
      def 			lowerCAmelCase__						(				self: List[str]   ):
             return 32
      @property
      def 			lowerCAmelCase__						(				self: Any   ):
             return self.time_input_dim * 4
      @property
      def 			lowerCAmelCase__						(				self: Dict   ):
             return 8
      @property
      def 			lowerCAmelCase__						(				self: int   ):
             torch.manual_seed(0   )
             __lowerCamelCase   =						CLIPVisionConfig(
                 hidden_size=self.text_embedder_hidden_size    ,       image_size=64    ,       projection_dim=self.text_embedder_hidden_size    ,       intermediate_size=37    ,       num_attention_heads=4    ,       num_channels=3    ,       num_hidden_layers=5    ,       patch_size=1    ,       )

             __lowerCamelCase   =						CLIPVisionModel(UpperCamelCase_   )
             return model
      @property
      def 			lowerCAmelCase__						(				self: Dict   ):
             __lowerCamelCase   =						CLIPImageProcessor(
                 crop_size=2_24    ,       do_center_crop=UpperCamelCase_    ,       do_normalize=UpperCamelCase_    ,       do_resize=UpperCamelCase_    ,       image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]    ,       image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]    ,       resample=3    ,       size=2_24    ,       )

             return image_processor
      @property
      def 			lowerCAmelCase__						(				self: Tuple   ):
             torch.manual_seed(0   )

             __lowerCamelCase   =						{
                 """num_attention_heads""": 2,
                 """attention_head_dim""": 16,
                 """embedding_dim""": self.time_input_dim,
                 """num_embeddings""": 32,
                 """embedding_proj_dim""": self.text_embedder_hidden_size,
                 """time_embed_dim""": self.time_embed_dim,
                 """num_layers""": 1,
                 """clip_embed_dim""": self.time_input_dim * 2,
                 """additional_embeddings""": 0,
                 """time_embed_act_fn""": """gelu""",
                 """norm_in_type""": """layer""",
                 """embedding_proj_norm_type""": """layer""",
                 """encoder_hid_proj_type""": None,
                 """added_emb_type""": None,
             }

             __lowerCamelCase   =						PriorTransformer(**UpperCamelCase_   )
             return model
      @property
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             torch.manual_seed(0   )

             __lowerCamelCase   =						{
                 """param_shapes""": (
                     (self.renderer_dim, 93),
                     (self.renderer_dim, 8),
                     (self.renderer_dim, 8),
                     (self.renderer_dim, 8),
                 ),
                 """d_latent""": self.time_input_dim,
                 """d_hidden""": self.renderer_dim,
                 """n_output""": 12,
                 """background""": (
                     0.1,
                     0.1,
                     0.1,
                 ),
             }
             __lowerCamelCase   =						ShapERenderer(**UpperCamelCase_   )
             return model
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						self.dummy_prior
             __lowerCamelCase   =						self.dummy_image_encoder
             __lowerCamelCase   =						self.dummy_image_processor
             __lowerCamelCase   =						self.dummy_renderer

             __lowerCamelCase   =						HeunDiscreteScheduler(
                 beta_schedule="""exp"""    ,       num_train_timesteps=10_24    ,       prediction_type="""sample"""    ,       use_karras_sigmas=UpperCamelCase_    ,       clip_sample=UpperCamelCase_    ,       clip_sample_range=1.0    ,       )
             __lowerCamelCase   =						{
                 """prior""": prior,
                 """image_encoder""": image_encoder,
                 """image_processor""": image_processor,
                 """renderer""": renderer,
                 """scheduler""": scheduler,
             }

             return components
      def 			lowerCAmelCase__						(				self: int    ,       UpperCamelCase_: List[Any]    ,       UpperCamelCase_: Dict=0   ):
             __lowerCamelCase   =						floats_tensor((1, 3, 64, 64)    ,       rng=random.Random(UpperCamelCase_   )   ).to(UpperCamelCase_   )

             if str(UpperCamelCase_   ).startswith("""mps"""   ):
                    __lowerCamelCase   =						torch.manual_seed(UpperCamelCase_   )
             else:
                    __lowerCamelCase   =						torch.Generator(device=UpperCamelCase_   ).manual_seed(UpperCamelCase_   )
             __lowerCamelCase   =						{
                 """image""": input_image,
                 """generator""": generator,
                 """num_inference_steps""": 1,
                 """frame_size""": 32,
                 """output_type""": """np""",
             }
             return inputs
      def 			lowerCAmelCase__						(				self: Tuple   ):
             __lowerCamelCase   =						"""cpu"""

             __lowerCamelCase   =						self.get_dummy_components()

             __lowerCamelCase   =						self.pipeline_class(**UpperCamelCase_   )
             __lowerCamelCase   =						pipe.to(UpperCamelCase_   )

             pipe.set_progress_bar_config(disable=UpperCamelCase_   )

             __lowerCamelCase   =						pipe(**self.get_dummy_inputs(UpperCamelCase_   )   )
             __lowerCamelCase   =						output.images[0]
             __lowerCamelCase   =						image[0, -3:, -3:, -1]

             assert image.shape == (20, 32, 32, 3)

             __lowerCamelCase   =						np.array(
                 [
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                     0.0003_9216,
                 ]   )

             assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
      def 			lowerCAmelCase__						(				self: List[str]   ):
             # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
             self._test_inference_batch_consistent(batch_sizes=[1, 2]   )
      def 			lowerCAmelCase__						(				self: Any   ):
             __lowerCamelCase   =						torch_device == """cpu"""
             __lowerCamelCase   =						True
             self._test_inference_batch_single_identical(
                 batch_size=2    ,       test_max_difference=UpperCamelCase_    ,       relax_max_difference=UpperCamelCase_    ,       )




      def 			lowerCAmelCase__						(				self: Any   ):
             __lowerCamelCase   =						self.get_dummy_components()
             __lowerCamelCase   =						self.pipeline_class(**UpperCamelCase_   )
             __lowerCamelCase   =						pipe.to(UpperCamelCase_   )
             pipe.set_progress_bar_config(disable=UpperCamelCase_   )

             __lowerCamelCase   =						1
             __lowerCamelCase   =						2

             __lowerCamelCase   =						self.get_dummy_inputs(UpperCamelCase_   )

             for key in inputs.keys():
                    if key in self.batch_params:
                           __lowerCamelCase   =						batch_size * [inputs[key]]

             __lowerCamelCase   =						pipe(**UpperCamelCase_    ,       num_images_per_prompt=UpperCamelCase_   )[0]

             assert images.shape[0] == batch_size * num_images_per_prompt





@slow
@require_torch_gpu
class     lowerCamelCase__(					unittest.TestCase):
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             # clean up the VRAM after each test
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()




      def 			lowerCAmelCase__						(				self: Any   ):
             __lowerCamelCase   =						load_image(
                 """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png"""   )
             __lowerCamelCase   =						load_numpy(
                 """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                 """/shap_e/test_shap_e_img2img_out.npy"""   )
             __lowerCamelCase   =						ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img"""   )
             __lowerCamelCase   =						pipe.to(UpperCamelCase_   )
             pipe.set_progress_bar_config(disable=UpperCamelCase_   )

             __lowerCamelCase   =						torch.Generator(device=UpperCamelCase_   ).manual_seed(0   )

             __lowerCamelCase   =						pipe(
                 UpperCamelCase_    ,       generator=UpperCamelCase_    ,       guidance_scale=3.0    ,       num_inference_steps=64    ,       frame_size=64    ,       output_type="""np"""    ,       ).images[0]

             assert images.shape == (20, 64, 64, 3)

             assert_mean_pixel_difference(UpperCamelCase_    ,       UpperCamelCase_   )





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


__lowercase	:						List[Any]       =	'bart'
__lowercase	:						Union[str, Any]       =	True






@st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE   )
def   lowerCamelCase							():
					if LOAD_DENSE_INDEX:
										__a			:       List[Any]					    =  AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased'   )
										__a			:       Dict					    =  AutoModel.from_pretrained('yjernite/retribert-base-uncased'   ).to('cuda:0'   )
										__a			:       Optional[int]					    =  qar_model.eval()
					else:
										__a    ,				__a			:       str					    =  (None, None)
					if MODEL_TYPE == "bart":
										__a			:       Union[str, Any]					    =  AutoTokenizer.from_pretrained('yjernite/bart_eli5'   )
										__a			:       int					    =  AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5'   ).to('cuda:0'   )
										__a			:       Optional[Any]					    =  torch.load('seq2seq_models/eli5_bart_model_blm_2.pth'   )
										sas_model.load_state_dict(save_dict['model']   )
										__a			:       str					    =  sas_model.eval()
					else:
										__a    ,				__a			:       Tuple					    =  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   lowerCamelCase							():
					if LOAD_DENSE_INDEX:
										__a			:       Optional[Any]					    =  faiss.StandardGpuResources()
										__a			:       Dict					    =  datasets.load_dataset(path='wiki_snippets'						,      name='wiki40b_en_100_0'   )['train']
										__a			:       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)						,      )
										__a			:       int					    =  faiss.IndexFlatIP(128   )
										__a			:       Any					    =  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:
										__a    ,				__a			:       str					    =  (None, None)
					__a			:       Optional[int]					    =  Elasticsearch([{'host': 'localhost', 'port': '9200'}]   )
					return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)






@st.cache(allow_output_mutation=_SCREAMING_SNAKE_CASE   )
def   lowerCamelCase							():
					__a			:       Dict					    =  datasets.load_dataset('eli5'						,      name='LFQA_reddit'   )
					__a			:       Dict					    =  elia['train_eli5']
					__a			:       Optional[int]					    =  np.memmap(
					    'eli5_questions_reps.dat'						,      dtype='float32'						,      mode='r'						,      shape=(elia_train.num_rows, 128)   )
					__a			:       str					    =  faiss.IndexFlatIP(128   )
					eli5_train_q_index.add(_SCREAMING_SNAKE_CASE   )
					return (elia_train, eli5_train_q_index)


__lowercase       ,      __lowercase       ,      __lowercase	:						Any       =	load_indexes()
__lowercase       ,      __lowercase       ,      __lowercase       ,      __lowercase	:						Dict       =	load_models()
__lowercase       ,      __lowercase	:						int       =	load_train_data()






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   int						,      _SCREAMING_SNAKE_CASE      :   List[str]=10   ):
					__a			:       Optional[int]					    =  embed_questions_for_retrieval([question]						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )
					__a    ,				__a			:       Union[str, Any]					    =  eli5_train_q_index.search(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )
					__a			:       Any					    =  [elia_train[int(_SCREAMING_SNAKE_CASE   )] for i in I[0]]
					return nn_examples






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Optional[int]						,      _SCREAMING_SNAKE_CASE      :   str="wiki40b"						,      _SCREAMING_SNAKE_CASE      :   List[str]="dense"						,      _SCREAMING_SNAKE_CASE      :   Any=10   ):
					if source == "none":
										__a    ,				__a			:       Any					    =  (' <P> '.join(['' for _ in range(11   )]   ).strip(), [])
					else:
										if method == "dense":
															__a    ,				__a			:       str					    =  query_qa_dense_index(
															    _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )
										else:
															__a    ,				__a			:       Union[str, Any]					    =  query_es_index(
															    _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      index_name='english_wiki40b_snippets_100w'						,      n_results=_SCREAMING_SNAKE_CASE						,      )
					__a			:       Dict					    =  [
					    (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst
					]
					__a			:       Any					    =  '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   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Union[str, Any]						,      _SCREAMING_SNAKE_CASE      :   str						,      _SCREAMING_SNAKE_CASE      :   Optional[int]						,      _SCREAMING_SNAKE_CASE      :   Dict=64						,      _SCREAMING_SNAKE_CASE      :   Dict=256						,      _SCREAMING_SNAKE_CASE      :   Any=False						,      _SCREAMING_SNAKE_CASE      :   Tuple=2						,      _SCREAMING_SNAKE_CASE      :   Union[str, Any]=0.9_5						,      _SCREAMING_SNAKE_CASE      :   str=0.8   ):
					with torch.no_grad():
										__a			:       Union[str, 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
__lowercase	:						Optional[Any]       =	'<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'
__lowercase	:						str       =	'\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
__lowercase	:						str       =	'\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)

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

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

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

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

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


__lowercase	:						List[Any]       =	'\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)



