import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402


__lowercase											=      {
    '''return_dict''': False,
    '''output_hidden_states''': True,
    '''output_attentions''': True,
    '''torchscript''': True,
    '''torch_dtype''': '''float16''',
    '''use_bfloat16''': True,
    '''tf_legacy_loss''': True,
    '''pruned_heads''': {'''a''': 1},
    '''tie_word_embeddings''': False,
    '''is_decoder''': True,
    '''cross_attention_hidden_size''': 128,
    '''add_cross_attention''': True,
    '''tie_encoder_decoder''': True,
    '''max_length''': 50,
    '''min_length''': 3,
    '''do_sample''': True,
    '''early_stopping''': True,
    '''num_beams''': 3,
    '''num_beam_groups''': 3,
    '''diversity_penalty''': 0.5,
    '''temperature''': 2.0,
    '''top_k''': 10,
    '''top_p''': 0.7,
    '''typical_p''': 0.2,
    '''repetition_penalty''': 0.8,
    '''length_penalty''': 0.8,
    '''no_repeat_ngram_size''': 5,
    '''encoder_no_repeat_ngram_size''': 5,
    '''bad_words_ids''': [1, 2, 3],
    '''num_return_sequences''': 3,
    '''chunk_size_feed_forward''': 5,
    '''output_scores''': True,
    '''return_dict_in_generate''': True,
    '''forced_bos_token_id''': 2,
    '''forced_eos_token_id''': 3,
    '''remove_invalid_values''': True,
    '''architectures''': ['''BertModel'''],
    '''finetuning_task''': '''translation''',
    '''id2label''': {0: '''label'''},
    '''label2id''': {'''label''': '''0'''},
    '''tokenizer_class''': '''BertTokenizerFast''',
    '''prefix''': '''prefix''',
    '''bos_token_id''': 6,
    '''pad_token_id''': 7,
    '''eos_token_id''': 8,
    '''sep_token_id''': 9,
    '''decoder_start_token_id''': 10,
    '''exponential_decay_length_penalty''': (5, 1.0_1),
    '''suppress_tokens''': [0, 1],
    '''begin_suppress_tokens''': 2,
    '''task_specific_params''': {'''translation''': '''some_params'''},
    '''problem_type''': '''regression''',
}


@is_staging_test
class 			lowerCamelCase_  (     unittest.TestCase				):






    '''simple docstring'''






    @classmethod
    def     UpperCamelCase__     (			cls) ->			List[str]:
        __UpperCamelCase  :Any    						=	TOKEN
        HfFolder.save_token(__lowercase)







    @classmethod
    def     UpperCamelCase__     (			cls) ->			int:
        try:
            delete_repo(token=cls._token				,				repo_id='''test-config''')
        except HTTPError:
            pass

        try:
            delete_repo(token=cls._token				,				repo_id='''valid_org/test-config-org''')
        except HTTPError:
            pass

        try:
            delete_repo(token=cls._token				,				repo_id='''test-dynamic-config''')
        except HTTPError:
            pass







    def     UpperCamelCase__     (			self) ->			List[Any]:
        __UpperCamelCase  :Optional[Any]    						=	BertConfig(
            vocab_size=99				,				hidden_size=32				,				num_hidden_layers=5				,				num_attention_heads=4				,				intermediate_size=37)
        config.push_to_hub('''test-config'''				,				use_auth_token=self._token)

        __UpperCamelCase  :Tuple    						=	BertConfig.from_pretrained(f"""{USER}/test-config""")
        for k, v in config.to_dict().items():
            if k != "transformers_version":
                self.assertEqual(__lowercase				,				getattr(__lowercase				,				__lowercase))

        # Reset repo
        delete_repo(token=self._token				,				repo_id='''test-config''')

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
            config.save_pretrained(__lowercase				,				repo_id='''test-config'''				,				push_to_hub=__lowercase				,				use_auth_token=self._token)

        __UpperCamelCase  :List[str]    						=	BertConfig.from_pretrained(f"""{USER}/test-config""")
        for k, v in config.to_dict().items():
            if k != "transformers_version":
                self.assertEqual(__lowercase				,				getattr(__lowercase				,				__lowercase))







    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        __UpperCamelCase  :Optional[int]    						=	BertConfig(
            vocab_size=99				,				hidden_size=32				,				num_hidden_layers=5				,				num_attention_heads=4				,				intermediate_size=37)
        config.push_to_hub('''valid_org/test-config-org'''				,				use_auth_token=self._token)

        __UpperCamelCase  :str    						=	BertConfig.from_pretrained('''valid_org/test-config-org''')
        for k, v in config.to_dict().items():
            if k != "transformers_version":
                self.assertEqual(__lowercase				,				getattr(__lowercase				,				__lowercase))

        # Reset repo
        delete_repo(token=self._token				,				repo_id='''valid_org/test-config-org''')

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
            config.save_pretrained(
                __lowercase				,				repo_id='''valid_org/test-config-org'''				,				push_to_hub=__lowercase				,				use_auth_token=self._token)

        __UpperCamelCase  :str    						=	BertConfig.from_pretrained('''valid_org/test-config-org''')
        for k, v in config.to_dict().items():
            if k != "transformers_version":
                self.assertEqual(__lowercase				,				getattr(__lowercase				,				__lowercase))







    def     UpperCamelCase__     (			self) ->			Optional[int]:
        CustomConfig.register_for_auto_class()
        __UpperCamelCase  :str    						=	CustomConfig(attribute=42)

        config.push_to_hub('''test-dynamic-config'''				,				use_auth_token=self._token)

        # This has added the proper auto_map field to the config
        self.assertDictEqual(config.auto_map				,				{'''AutoConfig''': '''custom_configuration.CustomConfig'''})

        __UpperCamelCase  :Any    						=	AutoConfig.from_pretrained(f"""{USER}/test-dynamic-config"""				,				trust_remote_code=__lowercase)
        # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
        self.assertEqual(new_config.__class__.__name__				,				'''CustomConfig''')
        self.assertEqual(new_config.attribute				,				42)


class 			lowerCamelCase_  (     unittest.TestCase				):






    '''simple docstring'''






    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        __UpperCamelCase  :Optional[Any]    						=	GPTaConfig()

        # attempt to modify each of int/float/bool/str config records and verify they were updated
        __UpperCamelCase  :List[str]    						=	c.n_embd + 1  # int
        __UpperCamelCase  :Any    						=	c.resid_pdrop + 1.0  # float
        __UpperCamelCase  :str    						=	not c.scale_attn_weights  # bool
        __UpperCamelCase  :Dict    						=	c.summary_type + '''foo'''  # str
        c.update_from_string(
            f"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""")
        self.assertEqual(__lowercase				,				c.n_embd				,				'''mismatch for key: n_embd''')
        self.assertEqual(__lowercase				,				c.resid_pdrop				,				'''mismatch for key: resid_pdrop''')
        self.assertEqual(__lowercase				,				c.scale_attn_weights				,				'''mismatch for key: scale_attn_weights''')
        self.assertEqual(__lowercase				,				c.summary_type				,				'''mismatch for key: summary_type''')







    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :Optional[Any]    						=	PretrainedConfig()
        __UpperCamelCase  :Optional[int]    						=	[key for key in base_config.__dict__ if key not in config_common_kwargs]
        # If this part of the test fails, you have arguments to addin config_common_kwargs above.
        self.assertListEqual(
            __lowercase				,				['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''])
        __UpperCamelCase  :Union[str, Any]    						=	[key for key, value in config_common_kwargs.items() if value == getattr(__lowercase				,				__lowercase)]
        if len(__lowercase) > 0:
            raise ValueError(
                '''The following keys are set with the default values in'''
                ''' `test_configuration_common.config_common_kwargs` pick another value for them:'''
                f""" {', '.join(__lowercase)}.""")







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        with self.assertRaises(__lowercase):
            # config is in subfolder, the following should not work without specifying the subfolder
            __UpperCamelCase  :Any    						=	BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''')

        __UpperCamelCase  :Optional[Any]    						=	BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder'''				,				subfolder='''bert''')

        self.assertIsNotNone(__lowercase)







    def     UpperCamelCase__     (			self) ->			str:
        # A mock response for an HTTP head request to emulate server down
        __UpperCamelCase  :int    						=	mock.Mock()
        __UpperCamelCase  :Dict    						=	500
        __UpperCamelCase  :Dict    						=	{}
        __UpperCamelCase  :Any    						=	HTTPError
        __UpperCamelCase  :Tuple    						=	{}

        # Download this model to make sure it's in the cache.
        __UpperCamelCase  :Union[str, Any]    						=	BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''')

        # Under the mock environment we get a 500 error when trying to reach the model.
        with mock.patch('''requests.Session.request'''				,				return_value=__lowercase) as mock_head:
            __UpperCamelCase  :int    						=	BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''')
            # This check we did call the fake head request
            mock_head.assert_called()







    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        # This test is for deprecated behavior and can be removed in v5
        __UpperCamelCase  :Optional[int]    						=	BertConfig.from_pretrained(
            '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''')







    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        __UpperCamelCase  :Any    						=	AutoConfig.from_pretrained('''bert-base-cased''')
        __UpperCamelCase  :Any    						=	['''config.4.0.0.json''']

        with tempfile.TemporaryDirectory() as tmp_dir:
            configuration.save_pretrained(__lowercase)
            __UpperCamelCase  :Any    						=	2
            json.dump(configuration.to_dict()				,				open(os.path.join(__lowercase				,				'''config.4.0.0.json''')				,				'''w'''))

            # This should pick the new configuration file as the version of Transformers is > 4.0.0
            __UpperCamelCase  :Union[str, Any]    						=	AutoConfig.from_pretrained(__lowercase)
            self.assertEqual(new_configuration.hidden_size				,				2)

            # Will need to be adjusted if we reach v42 and this test is still here.
            # Should pick the old configuration file as the version of Transformers is < 4.42.0
            __UpperCamelCase  :Tuple    						=	['''config.42.0.0.json''']
            __UpperCamelCase  :Union[str, Any]    						=	768
            configuration.save_pretrained(__lowercase)
            shutil.move(os.path.join(__lowercase				,				'''config.4.0.0.json''')				,				os.path.join(__lowercase				,				'''config.42.0.0.json'''))
            __UpperCamelCase  :Tuple    						=	AutoConfig.from_pretrained(__lowercase)
            self.assertEqual(new_configuration.hidden_size				,				768)







    def     UpperCamelCase__     (			self) ->			Tuple:
        # This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
        __UpperCamelCase  :Tuple    						=	'''hf-internal-testing/test-two-configs'''

        import transformers as new_transformers

        __UpperCamelCase  :Tuple    						=	'''v4.0.0'''
        __UpperCamelCase						, __UpperCamelCase  :Any    						=	new_transformers.models.auto.AutoConfig.from_pretrained(
            __lowercase				,				return_unused_kwargs=__lowercase)
        self.assertEqual(new_configuration.hidden_size				,				2)
        # This checks `_configuration_file` ia not kept in the kwargs by mistake.
        self.assertDictEqual(__lowercase				,				{})

        # Testing an older version by monkey-patching the version in the module it's used.
        import transformers as old_transformers

        __UpperCamelCase  :Optional[int]    						=	'''v3.0.0'''
        __UpperCamelCase  :str    						=	old_transformers.models.auto.AutoConfig.from_pretrained(__lowercase)
        self.assertEqual(old_configuration.hidden_size				,				768)






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											=      '''bart'''
__lowercase											=      True



@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE			)
def lowerCamelCase						(     ):
    '''simple docstring'''







    if LOAD_DENSE_INDEX:
        __UpperCamelCase  :Union[str, Any]    						=	AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased'''			)
        __UpperCamelCase  :Union[str, Any]    						=	AutoModel.from_pretrained('''yjernite/retribert-base-uncased'''			).to('''cuda:0'''			)
        __UpperCamelCase  :Optional[int]    						=	qar_model.eval()
    else:
        __UpperCamelCase						, __UpperCamelCase  :Optional[Any]    						=	(None, None)
    if MODEL_TYPE == "bart":
        __UpperCamelCase  :str    						=	AutoTokenizer.from_pretrained('''yjernite/bart_eli5'''			)
        __UpperCamelCase  :List[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  :List[str]    						=	sas_model.eval()
    else:
        __UpperCamelCase						, __UpperCamelCase  :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						(     ):
    '''simple docstring'''







    if LOAD_DENSE_INDEX:
        __UpperCamelCase  :int    						=	faiss.StandardGpuResources()
        __UpperCamelCase  :List[Any]    						=	datasets.load_dataset(path='''wiki_snippets'''						,    name='''wiki40b_en_100_0'''			)['''train''']
        __UpperCamelCase  :List[str]    						=	np.memmap(
            '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat'''						,    dtype='''float32'''						,    mode='''r'''						,    shape=(wikiaab_passages.num_rows, 128)						,    )
        __UpperCamelCase  :Tuple    						=	faiss.IndexFlatIP(128			)
        __UpperCamelCase  :str    						=	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:
        __UpperCamelCase						, __UpperCamelCase  :Any    						=	(None, None)
    __UpperCamelCase  :Optional[Any]    						=	Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}]			)
    return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)



@st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE			)
def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :Optional[Any]    						=	datasets.load_dataset('''eli5'''						,    name='''LFQA_reddit'''			)
    __UpperCamelCase  :int    						=	elia['''train_eli5''']
    __UpperCamelCase  :List[str]    						=	np.memmap(
        '''eli5_questions_reps.dat'''						,    dtype='''float32'''						,    mode='''r'''						,    shape=(elia_train.num_rows, 128)			)
    __UpperCamelCase  :Optional[Any]    						=	faiss.IndexFlatIP(128			)
    eli5_train_q_index.add(SCREAMING_SNAKE_CASE			)
    return (elia_train, eli5_train_q_index)


__lowercase				, __lowercase				, __lowercase											=      load_indexes()
__lowercase				, __lowercase				, __lowercase				, __lowercase											=      load_models()
__lowercase				, __lowercase											=      load_train_data()



def lowerCamelCase						(     SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE=10			):
    '''simple docstring'''







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



def lowerCamelCase						(     SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE="wiki40b"						,    SCREAMING_SNAKE_CASE="dense"						,    SCREAMING_SNAKE_CASE=10			):
    '''simple docstring'''







    if source == "none":
        __UpperCamelCase						, __UpperCamelCase  :Optional[int]    						=	(''' <P> '''.join(['''''' for _ in range(11			)]			).strip(), [])
    else:
        if method == "dense":
            __UpperCamelCase						, __UpperCamelCase  :List[str]    						=	query_qa_dense_index(
                SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE			)
        else:
            __UpperCamelCase						, __UpperCamelCase  :Optional[int]    						=	query_es_index(
                SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    index_name='''english_wiki40b_snippets_100w'''						,    n_results=SCREAMING_SNAKE_CASE						,    )
    __UpperCamelCase  :int    						=	[
        (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
    ]
    __UpperCamelCase  :int    						=	'''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						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE=64						,    SCREAMING_SNAKE_CASE=256						,    SCREAMING_SNAKE_CASE=False						,    SCREAMING_SNAKE_CASE=2						,    SCREAMING_SNAKE_CASE=0.95						,    SCREAMING_SNAKE_CASE=0.8			):
    '''simple docstring'''







    with torch.no_grad():
        __UpperCamelCase  :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											=      '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'''
__lowercase											=      '''
<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
__lowercase											=      '''
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)

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

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

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

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

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

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





