


"""simple docstring"""





import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

import pytest

import transformers
from transformers import (
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AutoTokenizer,
    BertConfig,
    BertTokenizer,
    BertTokenizerFast,
    CTRLTokenizer,
    GPTaTokenizer,
    GPTaTokenizerFast,
    PreTrainedTokenizerFast,
    RobertaTokenizer,
    RobertaTokenizerFast,
    is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
    TOKENIZER_MAPPING,
    get_tokenizer_config,
    tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
    DUMMY_DIFF_TOKENIZER_IDENTIFIER,
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tokenizers,
    slow,
)


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
 from test_module.custom_tokenization_fast import CustomTokenizerFast



class 						snake_case_(				unittest.TestCase	):






     def    lowerCamelCase__   (		self     :    Any ):
           lowerCAmelCase    :		List[Any]				=      0






     @slow
     def    lowerCamelCase__   (		self     :    Optional[int] ):
           for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
                 lowerCAmelCase    :		Union[str, Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
                 self.assertIsNotNone(UpperCamelCase_ )
                 self.assertIsInstance(UpperCamelCase_    , (BertTokenizer, BertTokenizerFast) )
                 self.assertGreater(len(UpperCamelCase_ )    , 0 )

           for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
                 lowerCAmelCase    :		Union[str, Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
                 self.assertIsNotNone(UpperCamelCase_ )
                 self.assertIsInstance(UpperCamelCase_    , (GPTaTokenizer, GPTaTokenizerFast) )
                 self.assertGreater(len(UpperCamelCase_ )    , 0 )






     def    lowerCamelCase__   (		self     :    List[Any] ):
           lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
           self.assertIsInstance(UpperCamelCase_    , (BertTokenizer, BertTokenizerFast) )
           self.assertEqual(tokenizer.vocab_size    , 1_2 )






     def    lowerCamelCase__   (		self     :    str ):
           lowerCAmelCase    :		Any				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
           self.assertIsInstance(UpperCamelCase_    , (RobertaTokenizer, RobertaTokenizerFast) )
           self.assertEqual(tokenizer.vocab_size    , 2_0 )






     def    lowerCamelCase__   (		self     :    Optional[int] ):
           lowerCAmelCase    :		List[Any]				=      AutoConfig.from_pretrained(UpperCamelCase_ )
           self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )
           # Check that tokenizer_type ≠ model_type
           lowerCAmelCase    :		List[str]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , config=UpperCamelCase_ )
           self.assertIsInstance(UpperCamelCase_    , (BertTokenizer, BertTokenizerFast) )
           self.assertEqual(tokenizer.vocab_size    , 1_2 )






     def    lowerCamelCase__   (		self     :    Optional[int] ):
           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.txt'''    , os.path.join(UpperCamelCase_    , '''vocab.txt''' ) )

                 lowerCAmelCase    :		int				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , tokenizer_type='''bert'''    , use_fast=UpperCamelCase_ )
                 self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )

           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.json'''    , os.path.join(UpperCamelCase_    , '''vocab.json''' ) )
                 shutil.copy('''./tests/fixtures/merges.txt'''    , os.path.join(UpperCamelCase_    , '''merges.txt''' ) )

                 lowerCAmelCase    :		Optional[Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , tokenizer_type='''gpt2'''    , use_fast=UpperCamelCase_ )
                 self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    List[str] ):
           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.txt'''    , os.path.join(UpperCamelCase_    , '''vocab.txt''' ) )

                 lowerCAmelCase    :		List[str]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , tokenizer_type='''bert''' )
                 self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )

           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.json'''    , os.path.join(UpperCamelCase_    , '''vocab.json''' ) )
                 shutil.copy('''./tests/fixtures/merges.txt'''    , os.path.join(UpperCamelCase_    , '''merges.txt''' ) )

                 lowerCAmelCase    :		Optional[Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , tokenizer_type='''gpt2''' )
                 self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           with pytest.raises(UpperCamelCase_ ):
                 AutoTokenizer.from_pretrained('''./'''    , tokenizer_type='''xxx''' )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
                 lowerCAmelCase    :		List[str]				=      tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' )
                 self.assertIsInstance(UpperCamelCase_    , (BertTokenizer, BertTokenizerFast) )

                 if isinstance(UpperCamelCase_    , UpperCamelCase_ ):
                       self.assertEqual(tokenizer.basic_tokenizer.do_lower_case    , UpperCamelCase_ )
                 else:
                       self.assertEqual(tokenizer.do_lower_case    , UpperCamelCase_ )

                 self.assertEqual(tokenizer.model_max_length    , 5_1_2 )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    Any ):
           for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
                 with self.assertRaisesRegex(
                     UpperCamelCase_    , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier'''    , ):
                       lowerCAmelCase    :		Optional[Any]				=      tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' )






     def    lowerCamelCase__   (		self     :    Any ):
           # tests: https://github.com/huggingface/transformers/pull/13251
           # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta
           # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai
           lowerCAmelCase    :		List[Any]				=      TOKENIZER_MAPPING.values()
           lowerCAmelCase    :		Tuple				=      []

           for slow_tok, fast_tok in tokenizers:
                 if slow_tok is not None:
                       tokenizer_names.append(slow_tok.__name__ )

                 if fast_tok is not None:
                       tokenizer_names.append(fast_tok.__name__ )

           for tokenizer_name in tokenizer_names:
                 # must find the right class
                 tokenizer_class_from_name(UpperCamelCase_ )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    Dict ):
           self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''    , use_fast=UpperCamelCase_ )    , UpperCamelCase_ )
           self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' )    , UpperCamelCase_ )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    int ):
           lowerCAmelCase    :		Union[str, Any]				=      AutoTokenizer.from_pretrained('''distilbert-base-uncased'''    , do_lower_case=UpperCamelCase_ )
           lowerCAmelCase    :		List[str]				=      '''Hello, world. How are you?'''
           lowerCAmelCase    :		Dict				=      tokenizer.tokenize(UpperCamelCase_ )
           self.assertEqual('''[UNK]'''    , tokens[0] )

           lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained('''microsoft/mpnet-base'''    , do_lower_case=UpperCamelCase_ )
           lowerCAmelCase    :		int				=      tokenizer.tokenize(UpperCamelCase_ )
           self.assertEqual('''[UNK]'''    , tokens[0] )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    Union[str, Any] ):
           lowerCAmelCase    :		List[Any]				=      AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' )
           self.assertEqual(type(UpperCamelCase_ )    , UpperCamelCase_ )
           self.assertEqual(tokenizer.model_max_length    , 5_1_2 )
           self.assertEqual(tokenizer.vocab_size    , 3_0_0_0_0 )
           self.assertEqual(tokenizer.unk_token    , '''[UNK]''' )
           self.assertEqual(tokenizer.padding_side    , '''right''' )
           self.assertEqual(tokenizer.truncation_side    , '''right''' )






     def    lowerCamelCase__   (		self     :    Dict ):
           lowerCAmelCase    :		Dict				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
           self.assertIsInstance(UpperCamelCase_    , (BertTokenizer, BertTokenizerFast) )
           with tempfile.TemporaryDirectory() as tmp_dir:
                 tokenizer.save_pretrained(UpperCamelCase_ )
                 lowerCAmelCase    :		Union[str, Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )

           self.assertIsInstance(UpperCamelCase_    , tokenizer.__class__ )
           self.assertEqual(tokenizera.vocab_size    , 1_2 )






     def    lowerCamelCase__   (		self     :    Tuple ):
           lowerCAmelCase    :		List[str]				=      AutoTokenizer.from_pretrained('''ctrl''' )
           # There is no fast CTRL so this always gives us a slow tokenizer.
           self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    str ):
           # Check we can load the tokenizer config of an online model.
           lowerCAmelCase    :		Union[str, Any]				=      get_tokenizer_config('''bert-base-cased''' )
           lowerCAmelCase    :		Optional[int]				=      config.pop('''_commit_hash'''    , UpperCamelCase_ )
           # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
           self.assertEqual(UpperCamelCase_    , {'''do_lower_case''': False} )

           # This model does not have a tokenizer_config so we get back an empty dict.
           lowerCAmelCase    :		str				=      get_tokenizer_config(UpperCamelCase_ )
           self.assertDictEqual(UpperCamelCase_    , {} )

           # A tokenizer saved with `save_pretrained` always creates a tokenizer config.
           lowerCAmelCase    :		Dict				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
           with tempfile.TemporaryDirectory() as tmp_dir:
                 tokenizer.save_pretrained(UpperCamelCase_ )
                 lowerCAmelCase    :		Tuple				=      get_tokenizer_config(UpperCamelCase_ )

           # Check the class of the tokenizer was properly saved (note that it always saves the slow class).
           self.assertEqual(config['''tokenizer_class''']    , '''BertTokenizer''' )






     def    lowerCamelCase__   (		self     :    Union[str, Any] ):
           try:
                 AutoConfig.register('''custom'''    , UpperCamelCase_ )

                 AutoTokenizer.register(UpperCamelCase_    , slow_tokenizer_class=UpperCamelCase_ )
                 # Trying to register something existing in the Transformers library will raise an error
                 with self.assertRaises(UpperCamelCase_ ):
                       AutoTokenizer.register(UpperCamelCase_    , slow_tokenizer_class=UpperCamelCase_ )

                 lowerCAmelCase    :		Dict				=      CustomTokenizer.from_pretrained(UpperCamelCase_ )
                 with tempfile.TemporaryDirectory() as tmp_dir:
                       tokenizer.save_pretrained(UpperCamelCase_ )

                       lowerCAmelCase    :		Any				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
                       self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )

           finally:
                 if "custom" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["custom"]
                 if CustomConfig in TOKENIZER_MAPPING._extra_content:
                       del TOKENIZER_MAPPING._extra_content[CustomConfig]






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    int ):
           try:
                 AutoConfig.register('''custom'''    , UpperCamelCase_ )

                 # Can register in two steps
                 AutoTokenizer.register(UpperCamelCase_    , slow_tokenizer_class=UpperCamelCase_ )
                 self.assertEqual(TOKENIZER_MAPPING[CustomConfig]    , (CustomTokenizer, None) )
                 AutoTokenizer.register(UpperCamelCase_    , fast_tokenizer_class=UpperCamelCase_ )
                 self.assertEqual(TOKENIZER_MAPPING[CustomConfig]    , (CustomTokenizer, CustomTokenizerFast) )

                 del TOKENIZER_MAPPING._extra_content[CustomConfig]
                 # Can register in one step
                 AutoTokenizer.register(
                     UpperCamelCase_    , slow_tokenizer_class=UpperCamelCase_    , fast_tokenizer_class=UpperCamelCase_ )
                 self.assertEqual(TOKENIZER_MAPPING[CustomConfig]    , (CustomTokenizer, CustomTokenizerFast) )

                 # Trying to register something existing in the Transformers library will raise an error
                 with self.assertRaises(UpperCamelCase_ ):
                       AutoTokenizer.register(UpperCamelCase_    , fast_tokenizer_class=UpperCamelCase_ )

                 # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
                 # and that model does not have a tokenizer.json
                 with tempfile.TemporaryDirectory() as tmp_dir:
                       lowerCAmelCase    :		Any				=      BertTokenizerFast.from_pretrained(UpperCamelCase_ )
                       bert_tokenizer.save_pretrained(UpperCamelCase_ )
                       lowerCAmelCase    :		int				=      CustomTokenizerFast.from_pretrained(UpperCamelCase_ )

                 with tempfile.TemporaryDirectory() as tmp_dir:
                       tokenizer.save_pretrained(UpperCamelCase_ )

                       lowerCAmelCase    :		Optional[Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_ )
                       self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )

                       lowerCAmelCase    :		Optional[int]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , use_fast=UpperCamelCase_ )
                       self.assertIsInstance(UpperCamelCase_    , UpperCamelCase_ )

           finally:
                 if "custom" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["custom"]
                 if CustomConfig in TOKENIZER_MAPPING._extra_content:
                       del TOKENIZER_MAPPING._extra_content[CustomConfig]






     def    lowerCamelCase__   (		self     :    Dict ):
           # If remote code is not set, we will time out when asking whether to load the model.
           with self.assertRaises(UpperCamelCase_ ):
                 lowerCAmelCase    :		Union[str, Any]				=      AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' )
           # If remote code is disabled, we can't load this config.
           with self.assertRaises(UpperCamelCase_ ):
                 lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_ )

           lowerCAmelCase    :		Optional[int]				=      AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_ )
           self.assertTrue(tokenizer.special_attribute_present )
           # Test tokenizer can be reloaded.
           with tempfile.TemporaryDirectory() as tmp_dir:
                 tokenizer.save_pretrained(UpperCamelCase_ )
                 lowerCAmelCase    :		Any				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , trust_remote_code=UpperCamelCase_ )
           self.assertTrue(reloaded_tokenizer.special_attribute_present )

           if is_tokenizers_available():
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizerFast''' )
                 self.assertEqual(reloaded_tokenizer.__class__.__name__    , '''NewTokenizerFast''' )

                 # Test we can also load the slow version
                 lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_    , use_fast=UpperCamelCase_ )
                 self.assertTrue(tokenizer.special_attribute_present )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 # Test tokenizer can be reloaded.
                 with tempfile.TemporaryDirectory() as tmp_dir:
                       tokenizer.save_pretrained(UpperCamelCase_ )
                       lowerCAmelCase    :		Any				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , trust_remote_code=UpperCamelCase_    , use_fast=UpperCamelCase_ )
                 self.assertEqual(reloaded_tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 self.assertTrue(reloaded_tokenizer.special_attribute_present )
           else:
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 self.assertEqual(reloaded_tokenizer.__class__.__name__    , '''NewTokenizer''' )






     @require_tokenizers
     def    lowerCamelCase__   (		self     :    int ):



           class 						snake_case_(				a__	):
                __UpperCamelCase     =    False



           class 						snake_case_(				a__	):
                __UpperCamelCase     =    NewTokenizer
                __UpperCamelCase     =    False

           try:
                 AutoConfig.register('''custom'''    , UpperCamelCase_ )
                 AutoTokenizer.register(UpperCamelCase_    , slow_tokenizer_class=UpperCamelCase_ )
                 AutoTokenizer.register(UpperCamelCase_    , fast_tokenizer_class=UpperCamelCase_ )
                 # If remote code is not set, the default is to use local
                 lowerCAmelCase    :		Tuple				=      AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizerFast''' )
                 self.assertFalse(tokenizer.special_attribute_present )
                 lowerCAmelCase    :		Dict				=      AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''    , use_fast=UpperCamelCase_ )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 self.assertFalse(tokenizer.special_attribute_present )

                 # If remote code is disabled, we load the local one.
                 lowerCAmelCase    :		Any				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_ )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizerFast''' )
                 self.assertFalse(tokenizer.special_attribute_present )
                 lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_    , use_fast=UpperCamelCase_ )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 self.assertFalse(tokenizer.special_attribute_present )

                 # If remote is enabled, we load from the Hub
                 lowerCAmelCase    :		Optional[int]				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_ )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizerFast''' )
                 self.assertTrue(tokenizer.special_attribute_present )
                 lowerCAmelCase    :		Dict				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer'''    , trust_remote_code=UpperCamelCase_    , use_fast=UpperCamelCase_ )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
                 self.assertTrue(tokenizer.special_attribute_present )

           finally:
                 if "custom" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["custom"]
                 if CustomConfig in TOKENIZER_MAPPING._extra_content:
                       del TOKENIZER_MAPPING._extra_content[CustomConfig]






     def    lowerCamelCase__   (		self     :    Dict ):
           lowerCAmelCase    :		List[str]				=      AutoTokenizer.from_pretrained(
               '''hf-internal-testing/test_dynamic_tokenizer_legacy'''    , trust_remote_code=UpperCamelCase_ )
           self.assertTrue(tokenizer.special_attribute_present )
           if is_tokenizers_available():
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizerFast''' )

                 # Test we can also load the slow version
                 lowerCAmelCase    :		List[Any]				=      AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer_legacy'''    , trust_remote_code=UpperCamelCase_    , use_fast=UpperCamelCase_ )
                 self.assertTrue(tokenizer.special_attribute_present )
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )
           else:
                 self.assertEqual(tokenizer.__class__.__name__    , '''NewTokenizer''' )






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           with self.assertRaisesRegex(
               UpperCamelCase_    , '''bert-base is not a local folder and is not a valid model identifier''' ):
                 lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained('''bert-base''' )






     def    lowerCamelCase__   (		self     :    Any ):
           with self.assertRaisesRegex(
               UpperCamelCase_    , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
                 lowerCAmelCase    :		Optional[Any]				=      AutoTokenizer.from_pretrained(UpperCamelCase_    , revision='''aaaaaa''' )






     def    lowerCamelCase__   (		self     :    Any ):
           # Make sure we have cached the tokenizer.
           lowerCAmelCase    :		str				=      AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' )
           with RequestCounter() as counter:
                 lowerCAmelCase    :		Optional[Any]				=      AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' )
                 self.assertEqual(counter.get_request_count    , 0 )
                 self.assertEqual(counter.head_request_count    , 1 )
                 self.assertEqual(counter.other_request_count    , 0 )






"""simple docstring"""





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

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


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


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


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


snake_case__ ,   snake_case__ ,   snake_case__						:   Optional[Any]			 = load_indexes()
snake_case__ ,   snake_case__ ,   snake_case__ ,   snake_case__						:   str			 = load_models()
snake_case__ ,   snake_case__						:   Union[str, Any]			 = load_train_data()


def    _snake_case  (  _snake_case :	int       ,      _snake_case :	Dict=10	):
      lowerCAmelCase    :		Tuple				=      embed_questions_for_retrieval([question]       ,      _snake_case       ,      _snake_case	)
      lowerCAmelCase,					lowerCAmelCase    :		Any				=      eli5_train_q_index.search(_snake_case       ,      _snake_case	)
      lowerCAmelCase    :		str				=      [elia_train[int(_snake_case	)] for i in I[0]]
      return nn_examples


def    _snake_case  (  _snake_case :	List[Any]       ,      _snake_case :	str="wiki40b"       ,      _snake_case :	List[str]="dense"       ,      _snake_case :	Union[str, Any]=10	):
      if source == "none":
            lowerCAmelCase,					lowerCAmelCase    :		List[str]				=      (''' <P> '''.join(['''''' for _ in range(11	)]	).strip(), [])
      else:
            if method == "dense":
                  lowerCAmelCase,					lowerCAmelCase    :		Tuple				=      query_qa_dense_index(
                      _snake_case       ,      _snake_case       ,      _snake_case       ,      _snake_case       ,      _snake_case       ,      _snake_case	)
            else:
                  lowerCAmelCase,					lowerCAmelCase    :		List[str]				=      query_es_index(
                      _snake_case       ,      _snake_case       ,      index_name='''english_wiki40b_snippets_100w'''       ,      n_results=_snake_case       ,      )
      lowerCAmelCase    :		int				=      [
          (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
      ]
      lowerCAmelCase    :		Any				=      '''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    _snake_case  (  _snake_case :	str       ,      _snake_case :	Dict       ,      _snake_case :	Dict       ,      _snake_case :	List[Any]=64       ,      _snake_case :	int=256       ,      _snake_case :	List[str]=False       ,      _snake_case :	Any=2       ,      _snake_case :	List[Any]=0.95       ,      _snake_case :	Tuple=0.8	):
      with torch.no_grad():
            lowerCAmelCase    :		Union[str, Any]				=      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=1024       ,      device='''cuda:0'''       ,      )[0]
      return (answer, support_list)


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

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

# Long Form QA with ELI5 and Wikipedia
snake_case__						:   List[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)

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

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

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

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

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


snake_case__						:   Any			 = '''
---

**Disclaimer**

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






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


