import tempfile
import unittest

from transformers import DPRConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
 from transformers.models.dpr.modeling_dpr import (
     DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
     DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
     DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
 )




class  __lowerCAmelCase	:



 '''simple docstring'''

 def __init__(      self							:		int							,      lowerCamelCase							:		int							,      lowerCamelCase							:		int=1_3							,      lowerCamelCase							:		Tuple=7							,      lowerCamelCase							:		Optional[Any]=False							,      lowerCamelCase							:		Optional[Any]=True							,      lowerCamelCase							:		Dict=True							,      lowerCamelCase							:		str=True							,      lowerCamelCase							:		int=9_9							,      lowerCamelCase							:		Optional[Any]=3_2							,      lowerCamelCase							:		Any=5							,      lowerCamelCase							:		Any=4							,      lowerCamelCase							:		Dict=3_7							,      lowerCamelCase							:		List[Any]="gelu"							,      lowerCamelCase							:		Optional[Any]=0.1							,      lowerCamelCase							:		int=0.1							,      lowerCamelCase							:		Optional[int]=5_1_2							,      lowerCamelCase							:		int=1_6							,      lowerCamelCase							:		List[Any]=2							,      lowerCamelCase							:		int=0.0_2							,      lowerCamelCase							:		Optional[int]=3							,      lowerCamelCase							:		Any=4							,      lowerCamelCase							:		Tuple=None							,      lowerCamelCase							:		int=0							,      )			->				Union[str, Any]:
        _UpperCamelCase  :							Union[str, Any]	    =	parent
        _UpperCamelCase  :							Optional[Any]	    =	batch_size
        _UpperCamelCase  :							List[str]	    =	seq_length
        _UpperCamelCase  :							str	    =	is_training
        _UpperCamelCase  :							Optional[Any]	    =	use_input_mask
        _UpperCamelCase  :							Optional[Any]	    =	use_token_type_ids
        _UpperCamelCase  :							Tuple	    =	use_labels
        _UpperCamelCase  :							int	    =	vocab_size
        _UpperCamelCase  :							Any	    =	hidden_size
        _UpperCamelCase  :							str	    =	num_hidden_layers
        _UpperCamelCase  :							Optional[Any]	    =	num_attention_heads
        _UpperCamelCase  :							Optional[Any]	    =	intermediate_size
        _UpperCamelCase  :							Any	    =	hidden_act
        _UpperCamelCase  :							List[str]	    =	hidden_dropout_prob
        _UpperCamelCase  :							Dict	    =	attention_probs_dropout_prob
        _UpperCamelCase  :							Optional[Any]	    =	max_position_embeddings
        _UpperCamelCase  :							Tuple	    =	type_vocab_size
        _UpperCamelCase  :							Optional[Any]	    =	type_sequence_label_size
        _UpperCamelCase  :							str	    =	initializer_range
        _UpperCamelCase  :							Union[str, Any]	    =	num_labels
        _UpperCamelCase  :							Optional[int]	    =	num_choices
        _UpperCamelCase  :							str	    =	scope
        _UpperCamelCase  :							int	    =	projection_dim

 def        __snake_case       (      self							:		Optional[Any]	)			->				Union[str, Any]:
        _UpperCamelCase  :							Union[str, Any]	    =	ids_tensor([self.batch_size, self.seq_length]							,      self.vocab_size	)

        _UpperCamelCase  :							List[Any]	    =	None
        if self.use_input_mask:
               _UpperCamelCase  :							Optional[int]	    =	random_attention_mask([self.batch_size, self.seq_length]	)

        _UpperCamelCase  :							Optional[int]	    =	None
        if self.use_token_type_ids:
               _UpperCamelCase  :							Union[str, Any]	    =	ids_tensor([self.batch_size, self.seq_length]							,      self.type_vocab_size	)

        _UpperCamelCase  :							Union[str, Any]	    =	None
        _UpperCamelCase  :							List[str]	    =	None
        _UpperCamelCase  :							Tuple	    =	None
        if self.use_labels:
               _UpperCamelCase  :							List[Any]	    =	ids_tensor([self.batch_size]							,      self.type_sequence_label_size	)
               _UpperCamelCase  :							Dict	    =	ids_tensor([self.batch_size, self.seq_length]							,      self.num_labels	)
               _UpperCamelCase  :							Dict	    =	ids_tensor([self.batch_size]							,      self.num_choices	)

        _UpperCamelCase  :							List[str]	    =	self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

 def        __snake_case       (      self							:		Optional[int]	)			->				Optional[int]:
        return DPRConfig(
            projection_dim=self.projection_dim							,      vocab_size=self.vocab_size							,      hidden_size=self.hidden_size							,      num_hidden_layers=self.num_hidden_layers							,      num_attention_heads=self.num_attention_heads							,      intermediate_size=self.intermediate_size							,      hidden_act=self.hidden_act							,      hidden_dropout_prob=self.hidden_dropout_prob							,      attention_probs_dropout_prob=self.attention_probs_dropout_prob							,      max_position_embeddings=self.max_position_embeddings							,      type_vocab_size=self.type_vocab_size							,      initializer_range=self.initializer_range							,      )

 def        __snake_case       (      self							:		Tuple							,      lowerCamelCase							:		Optional[Any]							,      lowerCamelCase							:		Dict							,      lowerCamelCase							:		Optional[int]							,      lowerCamelCase							:		List[str]							,      lowerCamelCase							:		Optional[int]							,      lowerCamelCase							:		Optional[int]							,      lowerCamelCase							:		str	)			->				Dict:
        _UpperCamelCase  :							Optional[int]	    =	DPRContextEncoder(config=lowerCamelCase	)
        model.to(lowerCamelCase	)
        model.eval()
        _UpperCamelCase  :							Optional[int]	    =	model(lowerCamelCase							,      attention_mask=lowerCamelCase							,      token_type_ids=lowerCamelCase	)
        _UpperCamelCase  :							Any	    =	model(lowerCamelCase							,      token_type_ids=lowerCamelCase	)
        _UpperCamelCase  :							Dict	    =	model(lowerCamelCase	)
        self.parent.assertEqual(result.pooler_output.shape							,      (self.batch_size, self.projection_dim or self.hidden_size)	)

 def        __snake_case       (      self							:		Dict							,      lowerCamelCase							:		Optional[Any]							,      lowerCamelCase							:		Union[str, Any]							,      lowerCamelCase							:		Any							,      lowerCamelCase							:		Dict							,      lowerCamelCase							:		Tuple							,      lowerCamelCase							:		Union[str, Any]							,      lowerCamelCase							:		Optional[Any]	)			->				Union[str, Any]:
        _UpperCamelCase  :							Optional[Any]	    =	DPRQuestionEncoder(config=lowerCamelCase	)
        model.to(lowerCamelCase	)
        model.eval()
        _UpperCamelCase  :							Any	    =	model(lowerCamelCase							,      attention_mask=lowerCamelCase							,      token_type_ids=lowerCamelCase	)
        _UpperCamelCase  :							Union[str, Any]	    =	model(lowerCamelCase							,      token_type_ids=lowerCamelCase	)
        _UpperCamelCase  :							int	    =	model(lowerCamelCase	)
        self.parent.assertEqual(result.pooler_output.shape							,      (self.batch_size, self.projection_dim or self.hidden_size)	)

 def        __snake_case       (      self							:		Optional[int]							,      lowerCamelCase							:		str							,      lowerCamelCase							:		Dict							,      lowerCamelCase							:		Union[str, Any]							,      lowerCamelCase							:		List[str]							,      lowerCamelCase							:		int							,      lowerCamelCase							:		Any							,      lowerCamelCase							:		List[str]	)			->				Any:
        _UpperCamelCase  :							Tuple	    =	DPRReader(config=lowerCamelCase	)
        model.to(lowerCamelCase	)
        model.eval()
        _UpperCamelCase  :							Union[str, Any]	    =	model(
            lowerCamelCase							,      attention_mask=lowerCamelCase							,      )

        self.parent.assertEqual(result.start_logits.shape							,      (self.batch_size, self.seq_length)	)
        self.parent.assertEqual(result.end_logits.shape							,      (self.batch_size, self.seq_length)	)
        self.parent.assertEqual(result.relevance_logits.shape							,      (self.batch_size,)	)

 def        __snake_case       (      self							:		List[Any]	)			->				str:
        _UpperCamelCase  :							Optional[Any]	    =	self.prepare_config_and_inputs()
        (
            (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   (
            _UpperCamelCase
        )    ,   
        )  :							Union[str, Any]	    =	config_and_inputs
        _UpperCamelCase  :							Dict	    =	{'input_ids': input_ids}
        return config, inputs_dict







@require_torch
class  __lowerCAmelCase	(							a_,						a_,						unittest.TestCase    ):



 '''simple docstring'''
 _lowerCamelCase    :						Union[str, Any]					     =			(
     (
         DPRContextEncoder,
         DPRQuestionEncoder,
         DPRReader,
     )
     if is_torch_available()
     else ()
 )
 _lowerCamelCase    :						Dict					     =			{'feature-extraction': DPRQuestionEncoder} if is_torch_available() else {}

 _lowerCamelCase    :						Union[str, Any]					     =			False
 _lowerCamelCase    :						List[Any]					     =			False  # why?
 _lowerCamelCase    :						Optional[Any]					     =			False
 _lowerCamelCase    :						List[Any]					     =			False

 def        __snake_case       (      self							:		Tuple	)			->				Optional[Any]:
        _UpperCamelCase  :							Union[str, Any]	    =	DPRModelTester(self	)
        _UpperCamelCase  :							Optional[int]	    =	ConfigTester(self							,      config_class=lowerCamelCase							,      hidden_size=3_7	)

 def        __snake_case       (      self							:		Tuple	)			->				List[str]:
        self.config_tester.run_common_tests()

 def        __snake_case       (      self							:		Dict	)			->				str:
        _UpperCamelCase  :							Union[str, Any]	    =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_context_encoder(*lowerCamelCase	)

 def        __snake_case       (      self							:		Optional[int]	)			->				str:
        _UpperCamelCase  :							Dict	    =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_question_encoder(*lowerCamelCase	)

 def        __snake_case       (      self							:		Union[str, Any]	)			->				Tuple:
        _UpperCamelCase  :							Union[str, Any]	    =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_reader(*lowerCamelCase	)

 def        __snake_case       (      self							:		Union[str, Any]	)			->				Dict:
        _UpperCamelCase  :							List[Any]	    =	self.model_tester.prepare_config_and_inputs()[0]

        _UpperCamelCase  :							Dict	    =	DPRQuestionEncoder(config=lowerCamelCase	)
        model.to(lowerCamelCase	)
        model.eval()

        with tempfile.TemporaryDirectory() as tmp_dirname:
               model.save_pretrained(lowerCamelCase	)
               _UpperCamelCase  :							List[Any]	    =	DPRQuestionEncoder.from_pretrained(lowerCamelCase							,      projection_dim=5_1_2	)

        self.assertIsNotNone(lowerCamelCase	)

 @slow
 def        __snake_case       (      self							:		int	)			->				int:
        for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCamelCase  :							Dict	    =	DPRContextEncoder.from_pretrained(lowerCamelCase	)
               self.assertIsNotNone(lowerCamelCase	)

        for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCamelCase  :							str	    =	DPRContextEncoder.from_pretrained(lowerCamelCase	)
               self.assertIsNotNone(lowerCamelCase	)

        for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCamelCase  :							Any	    =	DPRQuestionEncoder.from_pretrained(lowerCamelCase	)
               self.assertIsNotNone(lowerCamelCase	)

        for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCamelCase  :							List[str]	    =	DPRReader.from_pretrained(lowerCamelCase	)
               self.assertIsNotNone(lowerCamelCase	)







@require_torch
class  __lowerCAmelCase	(							unittest.TestCase    ):



 '''simple docstring'''

 @slow
 def        __snake_case       (      self							:		Tuple	)			->				List[str]:
        _UpperCamelCase  :							str	    =	DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'							,      return_dict=lowerCamelCase	)
        model.to(lowerCamelCase	)

        _UpperCamelCase  :							Optional[Any]	    =	torch.tensor(
            [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]							,      dtype=torch.long							,      device=lowerCamelCase	)  # [CLS] hello, is my dog cute? [SEP]
        _UpperCamelCase  :							Union[str, Any]	    =	model(lowerCamelCase	)[0]  # embedding shape = (1, 768)
        # compare the actual values for a slice.
        _UpperCamelCase  :							Tuple	    =	torch.tensor(
            [
                [
                    0.0_3_2_3_6_2_5_3,
                    0.1_2_7_5_3_3_3_5,
                    0.1_6_8_1_8_5_0_9,
                    0.0_0_2_7_9_7_8_6,
                    0.3_8_9_6_9_3_3,
                    0.2_4_2_6_4_9_4_5,
                    0.2_1_7_8_9_7_1,
                    -0.0_2_3_3_5_2_2_7,
                    -0.0_8_4_8_1_9_5_9,
                    -0.1_4_3_2_4_1_1_7,
                ]
            ]							,      dtype=torch.float							,      device=lowerCamelCase							,      )
        self.assertTrue(torch.allclose(output[:, :1_0]							,      lowerCamelCase							,      atol=1e-4	)	)

 @slow
 def        __snake_case       (      self							:		int	)			->				Optional[int]:
        _UpperCamelCase  :							Optional[int]	    =	DPRReaderTokenizer.from_pretrained('facebook/dpr-reader-single-nq-base'	)
        _UpperCamelCase  :							Optional[Any]	    =	DPRReader.from_pretrained('facebook/dpr-reader-single-nq-base'	)
        model.to(lowerCamelCase	)

        _UpperCamelCase  :							Tuple	    =	tokenizer(
            questions='What is love ?'							,      titles='Haddaway'							,      texts='What Is Love is a song recorded by the artist Haddaway'							,      padding=lowerCamelCase							,      return_tensors='pt'							,      )
        encoded_inputs.to(lowerCamelCase	)

        _UpperCamelCase  :							int	    =	model(**lowerCamelCase	)

        # compare the actual values for a slice.
        _UpperCamelCase  :							Optional[int]	    =	torch.tensor(
            [[-1_0.3_0_0_5, -1_0.7_7_6_5, -1_1.4_8_7_2, -1_1.6_8_4_1, -1_1.9_3_1_2, -1_0.3_0_0_2, -9.8_5_4_4, -1_1.7_3_7_8, -1_2.0_8_2_1, -1_0.2_9_7_5]]							,      dtype=torch.float							,      device=lowerCamelCase							,      )

        _UpperCamelCase  :							List[Any]	    =	torch.tensor(
            [[-1_1.0_6_8_4, -1_1.7_0_4_1, -1_1.5_3_9_7, -1_0.3_4_6_5, -1_0.8_7_9_1, -6.8_4_4_3, -1_1.9_9_5_9, -1_1.0_3_6_4, -1_0.0_0_9_6, -6.8_4_0_5]]							,      dtype=torch.float							,      device=lowerCamelCase							,      )
        self.assertTrue(torch.allclose(outputs.start_logits[:, :1_0]							,      lowerCamelCase							,      atol=1e-4	)	)
        self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0]							,      lowerCamelCase							,      atol=1e-4	)	)




import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np
import regex as re

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
 if is_torch_available():
  import torch
 if is_tf_available():
  import tensorflow as tf

from ...tokenization_utils import AddedToken, PreTrainedTokenizer


UpperCAmelCase      		=					logging.get_logger(__name__)

UpperCAmelCase      		=					{
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

UpperCAmelCase      		=					{
    '''vocab_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''',
    },
}

UpperCAmelCase      		=					{
    '''Salesforce/codegen-350M-mono''': 20_48,
}


@lru_cache()
def SCREAMING_SNAKE_CASE					(  ):
       _UpperCamelCase  :							Union[str, Any]	    =	(
           list(range(ord('!'					)		,    ord('~'					) + 1					)					) + list(range(ord('¡'					)		,    ord('¬'					) + 1					)					) + list(range(ord('®'					)		,    ord('ÿ'					) + 1					)					)
       )
       _UpperCamelCase  :							List[Any]	    =	bs[:]
       _UpperCamelCase  :							Optional[Any]	    =	0
       for b in range(2**8					):
              if b not in bs:
                     bs.append(lowercase_					)
                     cs.append(2**8 + n					)
                     n += 1
       _UpperCamelCase  :							int	    =	[chr(lowercase_					) for n in cs]
       return dict(zip(lowercase_		,    lowercase_					)					)


def SCREAMING_SNAKE_CASE					(  lowercase_:						Optional[int]					):
       _UpperCamelCase  :							Any	    =	set()
       _UpperCamelCase  :							str	    =	word[0]
       for char in word[1:]:
              pairs.add((prev_char, char)					)
              _UpperCamelCase  :							Optional[int]	    =	char
       return pairs





class  __lowerCAmelCase	(							a_    ):



 '''simple docstring'''
 _lowerCamelCase    :						int					     =			VOCAB_FILES_NAMES
 _lowerCamelCase    :						str					     =			PRETRAINED_VOCAB_FILES_MAP
 _lowerCamelCase    :						str					     =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCamelCase    :						Dict					     =			['input_ids', 'attention_mask']

 def __init__(      self							:		List[str]							,      lowerCamelCase							:		List[str]							,      lowerCamelCase							:		Tuple							,      lowerCamelCase							:		Union[str, Any]="replace"							,      lowerCamelCase							:		List[str]="<|endoftext|>"							,      lowerCamelCase							:		Union[str, Any]="<|endoftext|>"							,      lowerCamelCase							:		int="<|endoftext|>"							,      lowerCamelCase							:		str=None							,      lowerCamelCase							:		int=False							,      lowerCamelCase							:		Optional[int]=False							,      **lowerCamelCase							:		List[str]							,      )			->				Any:
        _UpperCamelCase  :							List[Any]	    =	AddedToken(lowerCamelCase							,      lstrip=lowerCamelCase							,      rstrip=lowerCamelCase	) if isinstance(lowerCamelCase							,      lowerCamelCase	) else bos_token
        _UpperCamelCase  :							Union[str, Any]	    =	AddedToken(lowerCamelCase							,      lstrip=lowerCamelCase							,      rstrip=lowerCamelCase	) if isinstance(lowerCamelCase							,      lowerCamelCase	) else eos_token
        _UpperCamelCase  :							str	    =	AddedToken(lowerCamelCase							,      lstrip=lowerCamelCase							,      rstrip=lowerCamelCase	) if isinstance(lowerCamelCase							,      lowerCamelCase	) else unk_token
        _UpperCamelCase  :							List[str]	    =	AddedToken(lowerCamelCase							,      lstrip=lowerCamelCase							,      rstrip=lowerCamelCase	) if isinstance(lowerCamelCase							,      lowerCamelCase	) else pad_token
        super().__init__(
            errors=lowerCamelCase							,      unk_token=lowerCamelCase							,      bos_token=lowerCamelCase							,      eos_token=lowerCamelCase							,      pad_token=lowerCamelCase							,      add_prefix_space=lowerCamelCase							,      add_bos_token=lowerCamelCase							,      **lowerCamelCase							,      )
        _UpperCamelCase  :							str	    =	add_bos_token

        with open(lowerCamelCase							,      encoding='utf-8'	) as vocab_handle:
               _UpperCamelCase  :							Tuple	    =	json.load(lowerCamelCase	)
        _UpperCamelCase  :							List[str]	    =	{v: k for k, v in self.encoder.items()}
        _UpperCamelCase  :							Any	    =	errors  # how to handle errors in decoding
        _UpperCamelCase  :							int	    =	bytes_to_unicode()
        _UpperCamelCase  :							Union[str, Any]	    =	{v: k for k, v in self.byte_encoder.items()}
        with open(lowerCamelCase							,      encoding='utf-8'	) as merges_handle:
               _UpperCamelCase  :							Optional[Any]	    =	merges_handle.read().split('\n'	)[1:-1]
        _UpperCamelCase  :							Optional[Any]	    =	[tuple(merge.split()	) for merge in bpe_merges]
        _UpperCamelCase  :							List[str]	    =	dict(zip(lowerCamelCase							,      range(len(lowerCamelCase	)	)	)	)
        _UpperCamelCase  :							Tuple	    =	{}
        _UpperCamelCase  :							Union[str, Any]	    =	add_prefix_space

        # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
        _UpperCamelCase  :							Union[str, Any]	    =	re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'	)

 @property
 def        __snake_case       (      self							:		Union[str, Any]	)			->				Any:
        return len(self.encoder	)

 def        __snake_case       (      self							:		Dict	)			->				int:
        return dict(self.encoder							,      **self.added_tokens_encoder	)

 def        __snake_case       (      self							:		List[Any]							,      lowerCamelCase							:		List[str]	)			->				Dict:
        if token in self.cache:
               return self.cache[token]
        _UpperCamelCase  :							List[str]	    =	tuple(lowerCamelCase	)
        _UpperCamelCase  :							Optional[Any]	    =	get_pairs(lowerCamelCase	)

        if not pairs:
               return token

        while True:
               _UpperCamelCase  :							Optional[int]	    =	min(lowerCamelCase							,      key=lambda lowerCamelCase	: self.bpe_ranks.get(lowerCamelCase							,      float('inf'	)	)	)
               if bigram not in self.bpe_ranks:
                      break
               _UpperCamelCase    ,   _UpperCamelCase  :							List[Any]	    =	bigram
               _UpperCamelCase  :							Optional[Any]	    =	[]
               _UpperCamelCase  :							str	    =	0
               while i < len(lowerCamelCase	):
                      try:
                             _UpperCamelCase  :							Optional[int]	    =	word.index(lowerCamelCase							,      lowerCamelCase	)
                      except ValueError:
                             new_word.extend(word[i:]	)
                             break
                      else:
                             new_word.extend(word[i:j]	)
                             _UpperCamelCase  :							Tuple	    =	j

                      if word[i] == first and i < len(lowerCamelCase	) - 1 and word[i + 1] == second:
                             new_word.append(first + second	)
                             i += 2
                      else:
                             new_word.append(word[i]	)
                             i += 1
               _UpperCamelCase  :							int	    =	tuple(lowerCamelCase	)
               _UpperCamelCase  :							List[Any]	    =	new_word
               if len(lowerCamelCase	) == 1:
                      break
               else:
                      _UpperCamelCase  :							Any	    =	get_pairs(lowerCamelCase	)
        _UpperCamelCase  :							Dict	    =	' '.join(lowerCamelCase	)
        _UpperCamelCase  :							int	    =	word
        return word

 def        __snake_case       (      self							:		str							,      lowerCamelCase							:		Dict							,      lowerCamelCase							:		Tuple=None	)			->				Dict:
        if self.add_bos_token:
               _UpperCamelCase  :							Dict	    =	[self.bos_token_id]
        else:
               _UpperCamelCase  :							Union[str, Any]	    =	[]

        _UpperCamelCase  :							str	    =	bos_token_ids + token_ids_a

        if token_ids_a is None:
               return output

        return output + bos_token_ids + token_ids_a

 def        __snake_case       (      self							:		int							,      lowerCamelCase							:		int	)			->				Optional[Any]:
        _UpperCamelCase  :							List[str]	    =	[]
        for token in re.findall(self.pat							,      lowerCamelCase	):
               _UpperCamelCase  :							Optional[int]	    =	''.join(
                   self.byte_encoder[b] for b in token.encode('utf-8'	)	)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
               bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase	).split(' '	)	)
        return bpe_tokens

 def        __snake_case       (      self							:		Any							,      lowerCamelCase							:		Union[str, Any]	)			->				Any:
        return self.encoder.get(lowerCamelCase							,      self.encoder.get(self.unk_token	)	)

 def        __snake_case       (      self							:		int							,      lowerCamelCase							:		List[Any]	)			->				Union[str, Any]:
        return self.decoder.get(lowerCamelCase	)

 def        __snake_case       (      self							:		List[str]							,      lowerCamelCase							:		Any	)			->				Optional[Any]:
        _UpperCamelCase  :							int	    =	''.join(lowerCamelCase	)
        _UpperCamelCase  :							Union[str, Any]	    =	bytearray([self.byte_decoder[c] for c in text]	).decode('utf-8'							,      errors=self.errors	)
        return text

 def        __snake_case       (      self							:		Dict							,      lowerCamelCase							:		str							,      lowerCamelCase							:		Optional[str] = None	)			->				Tuple[str]:
        if not os.path.isdir(lowerCamelCase	):
               logger.error(f"Vocabulary path ({save_directory}) should be a directory"	)
               return
        _UpperCamelCase  :							str	    =	os.path.join(
            lowerCamelCase							,      (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']	)
        _UpperCamelCase  :							Optional[Any]	    =	os.path.join(
            lowerCamelCase							,      (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']	)

        with open(lowerCamelCase							,      'w'							,      encoding='utf-8'	) as f:
               f.write(json.dumps(self.encoder							,      indent=2							,      sort_keys=lowerCamelCase							,      ensure_ascii=lowerCamelCase	) + '\n'	)

        _UpperCamelCase  :							Optional[Any]	    =	0
        with open(lowerCamelCase							,      'w'							,      encoding='utf-8'	) as writer:
               writer.write('#version: 0.2\n'	)
               for bpe_tokens, token_index in sorted(self.bpe_ranks.items()							,      key=lambda lowerCamelCase	: kv[1]	):
                      if index != token_index:
                             logger.warning(
                                 f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                                 ' Please check that the tokenizer is not corrupted!'	)
                             _UpperCamelCase  :							str	    =	token_index
                      writer.write(' '.join(lowerCamelCase	) + '\n'	)
                      index += 1

        return vocab_file, merge_file

 def        __snake_case       (      self							:		List[str]							,      lowerCamelCase							:		Union[str, Any]							,      lowerCamelCase							:		int=False							,      **lowerCamelCase							:		int	)			->				List[Any]:
        _UpperCamelCase  :							Dict	    =	kwargs.pop('add_prefix_space'							,      self.add_prefix_space	)
        if is_split_into_words or add_prefix_space:
               _UpperCamelCase  :							Any	    =	' ' + text
        return (text, kwargs)

 def        __snake_case       (      self							:		str							,      lowerCamelCase							:		Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"]							,      lowerCamelCase							:		bool = False							,      lowerCamelCase							:		bool = None							,      lowerCamelCase							:		Optional[List[str]] = None							,      **lowerCamelCase							:		List[str]							,      )			->				str:
        _UpperCamelCase  :							Optional[int]	    =	super()._decode(
            token_ids=lowerCamelCase							,      skip_special_tokens=lowerCamelCase							,      clean_up_tokenization_spaces=lowerCamelCase							,      **lowerCamelCase							,      )

        if truncate_before_pattern is not None and len(lowerCamelCase	) > 0:
               _UpperCamelCase  :							Optional[Any]	    =	self.truncate(lowerCamelCase							,      lowerCamelCase	)

        return decoded_text

 def        __snake_case       (      self							:		Optional[int]							,      lowerCamelCase							:		Union[str, Any]							,      lowerCamelCase							:		Any	)			->				Optional[int]:
        def find_re(lowerCamelCase							:		Any							,      lowerCamelCase							:		List[Any]							,      lowerCamelCase							:		str	):
               _UpperCamelCase  :							Optional[int]	    =	pattern.search(lowerCamelCase							,      lowerCamelCase	)
               return m.start() if m else -1

        _UpperCamelCase  :							Dict	    =	[re.compile(lowerCamelCase							,      re.MULTILINE	) for pattern in truncate_before_pattern]

        _UpperCamelCase  :							Union[str, Any]	    =	list(re.finditer('^print'							,      lowerCamelCase							,      re.MULTILINE	)	)

        if len(lowerCamelCase	) > 1:
               _UpperCamelCase  :							Tuple	    =	completion[: prints[1].start()]

        _UpperCamelCase  :							Union[str, Any]	    =	list(re.finditer('^def'							,      lowerCamelCase							,      re.MULTILINE	)	)

        if len(lowerCamelCase	) > 1:
               _UpperCamelCase  :							List[str]	    =	completion[: defs[1].start()]

        _UpperCamelCase  :							Tuple	    =	0

        _UpperCamelCase  :							List[str]	    =	[
            pos for pos in [find_re(lowerCamelCase							,      lowerCamelCase							,      lowerCamelCase	) for terminal in terminals] if pos != -1
        ]

        if len(lowerCamelCase	) > 0:
               return completion[: min(lowerCamelCase	)]
        else:
               return completion



