



import json
import os
from typing import Dict, List, Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


a_      :      Dict    =     logging.get_logger(__name__)


a_      :      Any    =     {
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
    'tokenizer_config_file': 'tokenizer_config.json',
}

a_      :      Union[str, Any]    =     {
    'vocab_file': {
        'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'
    },
    'merges_file': {
        'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'
    },
    'tokenizer_config_file': {
        'facebook/blenderbot_small-90M': (
            'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'
        )
    },
}

a_      :      List[Any]    =     {'facebook/blenderbot_small-90M': 5_12}






def     __a					(		__UpperCAmelCase       ):
 a__												= set()
 a__												= word[0]
 for char in word[1:]:
  pairs.add((prev_char, char)       )
  a__												= char

 a__												= set(__UpperCAmelCase       )
 return pairs

class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 _lowercase   :    Union[str, Any]      						=					VOCAB_FILES_NAMES
 _lowercase   :    List[Any]      						=					PRETRAINED_VOCAB_FILES_MAP
 _lowercase   :    Tuple      						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowercase   :    int      						=					['''input_ids''', '''attention_mask''']

 def __init__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE="__start__"		,				SCREAMING_SNAKE_CASE="__end__"		,				SCREAMING_SNAKE_CASE="__unk__"		,				SCREAMING_SNAKE_CASE="__null__"		,				**SCREAMING_SNAKE_CASE		,				) ->			List[str]:
  super().__init__(unk_token=SCREAMING_SNAKE_CASE		,				bos_token=SCREAMING_SNAKE_CASE		,				eos_token=SCREAMING_SNAKE_CASE		,				pad_token=SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      )

  with open(SCREAMING_SNAKE_CASE		,				encoding='''utf-8'''      ) as vocab_handle:
   a__												= json.load(SCREAMING_SNAKE_CASE      )
  a__												= {v: k for k, v in self.encoder.items()}
  with open(SCREAMING_SNAKE_CASE		,				encoding='''utf-8'''      ) as merges_handle:
   a__												= merges_handle.read().split('''\n'''      )[1:-1]
  a__												= [tuple(merge.split()      ) for merge in merges]
  a__												= dict(zip(SCREAMING_SNAKE_CASE		,				range(len(SCREAMING_SNAKE_CASE      )      )      )      )
  a__												= {}

 @property
 def 						_UpperCAmelCase       (	self      ) ->			int:
  return len(self.encoder      )

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

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE      ) ->			str:
  if token in self.cache:
   return self.cache[token]
  a__												= re.sub('''([.,!?()])'''		,				R''' \1'''		,				SCREAMING_SNAKE_CASE      )
  a__												= re.sub('''(\')'''		,				R''' \1 '''		,				SCREAMING_SNAKE_CASE      )
  a__												= re.sub(R'''\s{2,}'''		,				''' '''		,				SCREAMING_SNAKE_CASE      )
  if "\n" in token:
   a__												= token.replace('''\n'''		,				''' __newln__'''      )

  a__												= token.split(''' '''      )
  a__												= []
  for token in tokens:
   if not len(SCREAMING_SNAKE_CASE      ):
    continue

   a__												= token.lower()
   a__												= tuple(SCREAMING_SNAKE_CASE      )
   a__												= tuple(list(word[:-1]      ) + [word[-1] + '''</w>''']      )
   a__												= get_pairs(SCREAMING_SNAKE_CASE      )

   if not pairs:
    words.append(SCREAMING_SNAKE_CASE      )
    continue

   while True:
    a__												= min(SCREAMING_SNAKE_CASE		,				key=lambda SCREAMING_SNAKE_CASE      : self.bpe_ranks.get(SCREAMING_SNAKE_CASE		,				float('''inf'''      )      )      )
    if bigram not in self.bpe_ranks:
     break
    a__							,			a__												= bigram
    a__												= []
    a__												= 0

    while i < len(SCREAMING_SNAKE_CASE      ):
     try:
      a__												= word.index(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      )
      new_word.extend(word[i:j]      )
      a__												= j
     except ValueError:
      new_word.extend(word[i:]      )
      break

     if word[i] == first and i < len(SCREAMING_SNAKE_CASE      ) - 1 and word[i + 1] == second:
      new_word.append(first + second      )
      i += 2
     else:
      new_word.append(word[i]      )
      i += 1
    a__												= tuple(SCREAMING_SNAKE_CASE      )
    a__												= new_word
    if len(SCREAMING_SNAKE_CASE      ) == 1:
     break
    else:
     a__												= get_pairs(SCREAMING_SNAKE_CASE      )
   a__												= '''@@ '''.join(SCREAMING_SNAKE_CASE      )
   a__												= word[:-4]

   a__												= word
   words.append(SCREAMING_SNAKE_CASE      )
  return " ".join(SCREAMING_SNAKE_CASE      )

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE      ) ->			List[str]:
  a__												= []

  a__												= re.findall(R'''\S+\n?'''		,				SCREAMING_SNAKE_CASE      )

  for token in words:
   split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE      ).split(''' '''      )      )      )
  return split_tokens

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE      ) ->			int:
  a__												= token.lower()
  return self.encoder.get(SCREAMING_SNAKE_CASE		,				self.encoder.get(self.unk_token      )      )

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE      ) ->			str:
  return self.decoder.get(SCREAMING_SNAKE_CASE		,				self.unk_token      )

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE      ) ->			str:
  a__												= ''' '''.join(SCREAMING_SNAKE_CASE      ).replace('''@@ '''		,				''''''      ).strip()
  return out_string



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

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

  a__												= 0
  with open(SCREAMING_SNAKE_CASE		,				'''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 SCREAMING_SNAKE_CASE      : 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!'''      )
     a__												= token_index
    writer.write(''' '''.join(SCREAMING_SNAKE_CASE      ) + '''\n'''      )
    index += 1

  return vocab_file, merge_file










import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
     pass

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a_      :      Union[str, Any]    =     logging.get_logger(__name__)

a_      :      Optional[Any]    =     {
    'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}
class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 _lowercase   :    int      						=					'''align_text_model'''

 def __init__(	self		,				SCREAMING_SNAKE_CASE=3_0_5_2_2		,				SCREAMING_SNAKE_CASE=7_6_8		,				SCREAMING_SNAKE_CASE=1_2		,				SCREAMING_SNAKE_CASE=1_2		,				SCREAMING_SNAKE_CASE=3_0_7_2		,				SCREAMING_SNAKE_CASE="gelu"		,				SCREAMING_SNAKE_CASE=0.1		,				SCREAMING_SNAKE_CASE=0.1		,				SCREAMING_SNAKE_CASE=5_1_2		,				SCREAMING_SNAKE_CASE=2		,				SCREAMING_SNAKE_CASE=0.02		,				SCREAMING_SNAKE_CASE=1e-1_2		,				SCREAMING_SNAKE_CASE=0		,				SCREAMING_SNAKE_CASE="absolute"		,				SCREAMING_SNAKE_CASE=True		,				**SCREAMING_SNAKE_CASE		,				) ->			List[str]:
  super().__init__(**SCREAMING_SNAKE_CASE      )

  a__												= vocab_size
  a__												= hidden_size
  a__												= num_hidden_layers
  a__												= num_attention_heads
  a__												= hidden_act
  a__												= intermediate_size
  a__												= hidden_dropout_prob
  a__												= attention_probs_dropout_prob
  a__												= max_position_embeddings
  a__												= type_vocab_size
  a__												= initializer_range
  a__												= layer_norm_eps
  a__												= position_embedding_type
  a__												= use_cache
  a__												= pad_token_id



 @classmethod
 def 						_UpperCAmelCase       (	cls		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			"PretrainedConfig":
  cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE      )

  a__							,			a__												= cls.get_config_dict(SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      )

  # get the text config dict if we are loading from AlignConfig
  if config_dict.get('''model_type'''      ) == "align":
   a__												= config_dict['''text_config''']

  if "model_type" in config_dict and hasattr(cls		,				'''model_type'''      ) and config_dict["model_type"] != cls.model_type:
   logger.warning(
       f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
       f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."      )

  return cls.from_dict(SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      )





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 _lowercase   :    str      						=					'''align_vision_model'''

 def __init__(	self		,				SCREAMING_SNAKE_CASE = 3		,				SCREAMING_SNAKE_CASE = 6_0_0		,				SCREAMING_SNAKE_CASE = 2.0		,				SCREAMING_SNAKE_CASE = 3.1		,				SCREAMING_SNAKE_CASE = 8		,				SCREAMING_SNAKE_CASE = [3, 3, 5, 3, 5, 5, 3]		,				SCREAMING_SNAKE_CASE = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2]		,				SCREAMING_SNAKE_CASE = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0]		,				SCREAMING_SNAKE_CASE = []		,				SCREAMING_SNAKE_CASE = [1, 2, 2, 2, 1, 2, 1]		,				SCREAMING_SNAKE_CASE = [1, 2, 2, 3, 3, 4, 1]		,				SCREAMING_SNAKE_CASE = [1, 6, 6, 6, 6, 6, 6]		,				SCREAMING_SNAKE_CASE = 0.25		,				SCREAMING_SNAKE_CASE = "swish"		,				SCREAMING_SNAKE_CASE = 2_5_6_0		,				SCREAMING_SNAKE_CASE = "mean"		,				SCREAMING_SNAKE_CASE = 0.02		,				SCREAMING_SNAKE_CASE = 0.0_01		,				SCREAMING_SNAKE_CASE = 0.99		,				SCREAMING_SNAKE_CASE = 0.2		,				**SCREAMING_SNAKE_CASE		,				) ->			str:
  super().__init__(**SCREAMING_SNAKE_CASE      )

  a__												= num_channels
  a__												= image_size
  a__												= width_coefficient
  a__												= depth_coefficient
  a__												= depth_divisor
  a__												= kernel_sizes
  a__												= in_channels
  a__												= out_channels
  a__												= depthwise_padding
  a__												= strides
  a__												= num_block_repeats
  a__												= expand_ratios
  a__												= squeeze_expansion_ratio
  a__												= hidden_act
  a__												= hidden_dim
  a__												= pooling_type
  a__												= initializer_range
  a__												= batch_norm_eps
  a__												= batch_norm_momentum
  a__												= drop_connect_rate
  a__												= sum(SCREAMING_SNAKE_CASE      ) * 4



 @classmethod
 def 						_UpperCAmelCase       (	cls		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			"PretrainedConfig":
  cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE      )

  a__							,			a__												= cls.get_config_dict(SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      )

  # get the vision config dict if we are loading from AlignConfig
  if config_dict.get('''model_type'''      ) == "align":
   a__												= config_dict['''vision_config''']

  if "model_type" in config_dict and hasattr(cls		,				'''model_type'''      ) and config_dict["model_type"] != cls.model_type:
   logger.warning(
       f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
       f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."      )

  return cls.from_dict(SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      )





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 _lowercase   :    Dict      						=					'''align'''
 _lowercase   :    Optional[Any]      						=					True

 def __init__(	self		,				SCREAMING_SNAKE_CASE=None		,				SCREAMING_SNAKE_CASE=None		,				SCREAMING_SNAKE_CASE=6_4_0		,				SCREAMING_SNAKE_CASE=1.0		,				SCREAMING_SNAKE_CASE=0.02		,				**SCREAMING_SNAKE_CASE		,				) ->			List[str]:
  super().__init__(**SCREAMING_SNAKE_CASE      )

  if text_config is None:
   a__												= {}
   logger.info('''text_config is None. Initializing the AlignTextConfig with default values.'''      )

  if vision_config is None:
   a__												= {}
   logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.'''      )

  a__												= AlignTextConfig(**SCREAMING_SNAKE_CASE      )
  a__												= AlignVisionConfig(**SCREAMING_SNAKE_CASE      )

  a__												= projection_dim
  a__												= temperature_init_value
  a__												= initializer_range

 @classmethod
 def 						_UpperCAmelCase       (	cls		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			Optional[int]:
  return cls(text_config=text_config.to_dict()		,				vision_config=vision_config.to_dict()		,				**SCREAMING_SNAKE_CASE      )



 def 						_UpperCAmelCase       (	self      ) ->			int:
  a__												= copy.deepcopy(self.__dict__      )
  a__												= self.text_config.to_dict()
  a__												= self.vision_config.to_dict()
  a__												= self.__class__.model_type
  return output





