
"""simple docstring"""



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


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

a					:	Any							=		'''▁'''

a					:	List[str]							=		{'''vocab_file''': '''sentencepiece.bpe.model'''}

a					:	Tuple							=		{
    '''vocab_file''': {
        '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''',
    }
}

a					:	Optional[int]							=		{
    '''facebook/xglm-564M''': 2_0_4_8,
}




class 		a_						( _UpperCAmelCase	):
    a      :				int     =				VOCAB_FILES_NAMES
    a      :				str     =				PRETRAINED_VOCAB_FILES_MAP
    a      :				Any     =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    a      :				Optional[int]     =				['input_ids', 'attention_mask']







    def __init__(			self			:       Dict     ,					__UpperCamelCase			:       List[str]     ,					__UpperCamelCase			:       Any="<s>"     ,					__UpperCamelCase			:       Union[str, Any]="</s>"     ,					__UpperCamelCase			:       Optional[Any]="</s>"     ,					__UpperCamelCase			:       List[str]="<s>"     ,					__UpperCamelCase			:       Optional[int]="<unk>"     ,					__UpperCamelCase			:       Union[str, Any]="<pad>"     ,					__UpperCamelCase			:       Optional[Dict[str, Any]] = None     ,					**__UpperCamelCase			:       List[Any]     ,					)		->None:






        '''simple docstring'''






        _UpperCAmelCase          =   {} if sp_model_kwargs is None else sp_model_kwargs

        # Compatibility with the original tokenizer
        _UpperCAmelCase          =   7
        _UpperCAmelCase          =   [f"""<madeupword{i}>""" for i in range(self.num_madeup_words     )]

        _UpperCAmelCase          =   kwargs.get("""additional_special_tokens"""     ,					[]     )
        kwargs["additional_special_tokens"] += [
            word for word in madeup_words if word not in kwargs["additional_special_tokens"]
        ]

        super().__init__(
            bos_token=__UpperCamelCase     ,					eos_token=__UpperCamelCase     ,					unk_token=__UpperCamelCase     ,					sep_token=__UpperCamelCase     ,					cls_token=__UpperCamelCase     ,					pad_token=__UpperCamelCase     ,					sp_model_kwargs=self.sp_model_kwargs     ,					**__UpperCamelCase     ,					)

        _UpperCAmelCase          =   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
        self.sp_model.Load(str(__UpperCamelCase     )     )
        _UpperCAmelCase          =   vocab_file

        # Original fairseq vocab and spm vocab must be "aligned":
        # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
        # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
        # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
        # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

        # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
        _UpperCAmelCase          =   1

        # Mimic fairseq token-to-id alignment for the first 4 token
        _UpperCAmelCase          =   {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

        _UpperCAmelCase          =   len(self.sp_model     )
        _UpperCAmelCase          =   {f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words     )}
        self.fairseq_tokens_to_ids.update(__UpperCamelCase     )

        _UpperCAmelCase          =   {v: k for k, v in self.fairseq_tokens_to_ids.items()}







    def __getstate__(			self			:       Optional[Any]     )		->str:






        '''simple docstring'''






        _UpperCAmelCase          =   self.__dict__.copy()
        _UpperCAmelCase          =   None
        _UpperCAmelCase          =   self.sp_model.serialized_model_proto()
        return state







    def __setstate__(			self			:       Dict     ,					__UpperCamelCase			:       Optional[Any]     )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase          =   d

        # for backward compatibility
        if not hasattr(self     ,					"""sp_model_kwargs"""     ):
            _UpperCAmelCase          =   {}

        _UpperCAmelCase          =   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto     )







    def      _snake_case					(			self			:       Optional[int]     ,					__UpperCamelCase			:       List[int]     ,					__UpperCamelCase			:       Optional[List[int]] = None     )		->List[int]:






        '''simple docstring'''






        if token_ids_a is None:
            return [self.sep_token_id] + token_ids_a
        _UpperCAmelCase          =   [self.sep_token_id]
        return sep + token_ids_a + sep + sep + token_ids_a







    def      _snake_case					(			self			:       Dict     ,					__UpperCamelCase			:       List[int]     ,					__UpperCamelCase			:       Optional[List[int]] = None     ,					__UpperCamelCase			:       bool = False     )		->List[int]:






        '''simple docstring'''






        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_a=__UpperCamelCase     ,					token_ids_a=__UpperCamelCase     ,					already_has_special_tokens=__UpperCamelCase     )

        if token_ids_a is None:
            return [1] + ([0] * len(__UpperCamelCase     ))
        return [1] + ([0] * len(__UpperCamelCase     )) + [1, 1] + ([0] * len(__UpperCamelCase     ))







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       List[int]     ,					__UpperCamelCase			:       Optional[List[int]] = None     )		->List[int]:






        '''simple docstring'''






        _UpperCAmelCase          =   [self.sep_token_id]

        if token_ids_a is None:
            return len(sep + token_ids_a     ) * [0]
        return len(sep + token_ids_a + sep + sep + token_ids_a     ) * [0]







    @property
    def      _snake_case					(			self			:       Optional[Any]     )		->Optional[int]:






        '''simple docstring'''






        return len(self.sp_model     ) + self.fairseq_offset + self.num_madeup_words







    def      _snake_case					(			self			:       str     )		->Optional[int]:






        '''simple docstring'''






        _UpperCAmelCase          =   {self.convert_ids_to_tokens(__UpperCamelCase     ): i for i in range(self.vocab_size     )}
        vocab.update(self.added_tokens_encoder     )
        return vocab







    def      _snake_case					(			self			:       Optional[int]     ,					__UpperCamelCase			:       str     )		->List[str]:






        '''simple docstring'''






        return self.sp_model.encode(__UpperCamelCase     ,					out_type=__UpperCamelCase     )







    def      _snake_case					(			self			:       List[Any]     ,					__UpperCamelCase			:       Dict     )		->List[str]:






        '''simple docstring'''






        if token in self.fairseq_tokens_to_ids:
            return self.fairseq_tokens_to_ids[token]
        _UpperCAmelCase          =   self.sp_model.PieceToId(__UpperCamelCase     )

        # Need to return unknown token if the SP model returned 0
        return spm_id + self.fairseq_offset if spm_id else self.unk_token_id







    def      _snake_case					(			self			:       Tuple     ,					__UpperCamelCase			:       Union[str, Any]     )		->str:






        '''simple docstring'''






        if index in self.fairseq_ids_to_tokens:
            return self.fairseq_ids_to_tokens[index]
        return self.sp_model.IdToPiece(index - self.fairseq_offset     )







    def      _snake_case					(			self			:       Optional[Any]     ,					__UpperCamelCase			:       List[str]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   """""".join(__UpperCamelCase     ).replace(__UpperCamelCase     ,					""" """     ).strip()
        return out_string







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       str     ,					__UpperCamelCase			:       Optional[str] = None     )		->Tuple[str]:






        '''simple docstring'''






        if not os.path.isdir(__UpperCamelCase     ):
            logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""     )
            return
        _UpperCAmelCase          =   os.path.join(
            __UpperCamelCase     ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]     )

        if os.path.abspath(self.vocab_file     ) != os.path.abspath(__UpperCamelCase     ) and os.path.isfile(self.vocab_file     ):
            copyfile(self.vocab_file     ,					__UpperCamelCase     )
        elif not os.path.isfile(self.vocab_file     ):
            with open(__UpperCamelCase     ,					"""wb"""     ) as fi:
                _UpperCAmelCase          =   self.sp_model.serialized_model_proto()
                fi.write(__UpperCamelCase     )

        return (out_vocab_file,)

"""simple docstring"""



import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin




class 		a_						( _UpperCAmelCase	):
    a      :				Any     =				['image_processor', 'tokenizer']
    a      :				Optional[int]     =				'AutoImageProcessor'
    a      :				Any     =				'AutoTokenizer'







    def __init__(			self			:       List[str]     ,					__UpperCamelCase			:       List[Any]=None     ,					__UpperCamelCase			:       List[str]=None     ,					**__UpperCamelCase			:       List[Any]     )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase          =   None
        if "feature_extractor" in kwargs:
            warnings.warn(
                """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                """ instead."""     ,					__UpperCamelCase     ,					)
            _UpperCAmelCase          =   kwargs.pop("""feature_extractor"""     )

        _UpperCAmelCase          =   image_processor if image_processor is not None else feature_extractor
        if image_processor is None:
            raise ValueError("""You need to specify an `image_processor`."""     )
        if tokenizer is None:
            raise ValueError("""You need to specify a `tokenizer`."""     )

        super().__init__(__UpperCamelCase     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   self.image_processor
        _UpperCAmelCase          =   False







    def __call__(			self			:       Union[str, Any]     ,					*__UpperCamelCase			:       str     ,					**__UpperCamelCase			:       Optional[Any]     )		->List[str]:






        '''simple docstring'''






        if self._in_target_context_manager:
            return self.current_processor(*__UpperCamelCase     ,					**__UpperCamelCase     )

        _UpperCAmelCase          =   kwargs.pop("""images"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   kwargs.pop("""text"""     ,					__UpperCamelCase     )
        if len(__UpperCamelCase     ) > 0:
            _UpperCAmelCase          =   args[0]
            _UpperCAmelCase          =   args[1:]

        if images is None and text is None:
            raise ValueError("""You need to specify either an `images` or `text` input to process."""     )

        if images is not None:
            _UpperCAmelCase          =   self.image_processor(__UpperCamelCase     ,					*__UpperCamelCase     ,					**__UpperCamelCase     )
        if text is not None:
            _UpperCAmelCase          =   self.tokenizer(__UpperCamelCase     ,					**__UpperCamelCase     )

        if text is None:
            return inputs
        elif images is None:
            return encodings
        else:
            _UpperCAmelCase          =   encodings["""input_ids"""]
            return inputs







    def      _snake_case					(			self			:       Union[str, Any]     ,					*__UpperCamelCase			:       int     ,					**__UpperCamelCase			:       Tuple     )		->Tuple:






        '''simple docstring'''






        return self.tokenizer.batch_decode(*__UpperCamelCase     ,					**__UpperCamelCase     )







    def      _snake_case					(			self			:       Tuple     ,					*__UpperCamelCase			:       int     ,					**__UpperCamelCase			:       Union[str, Any]     )		->int:






        '''simple docstring'''






        return self.tokenizer.decode(*__UpperCamelCase     ,					**__UpperCamelCase     )







    @contextmanager
    def      _snake_case					(			self			:       Tuple     )		->Union[str, Any]:






        '''simple docstring'''






        warnings.warn(
            """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
            """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
            """your images inputs, or in a separate call."""     )
        _UpperCAmelCase          =   True
        _UpperCAmelCase          =   self.tokenizer
        yield
        _UpperCAmelCase          =   self.image_processor
        _UpperCAmelCase          =   False







    def      _snake_case					(			self			:       str     ,					__UpperCamelCase			:       Dict     ,					__UpperCamelCase			:       Optional[Any]=False     ,					__UpperCamelCase			:       Union[str, Any]=None     )		->List[str]:






        '''simple docstring'''






        if added_vocab is None:
            _UpperCAmelCase          =   self.tokenizer.get_added_vocab()

        _UpperCAmelCase          =   {}

        while tokens:
            _UpperCAmelCase          =   re.search(r"""<s_(.*?)>"""     ,					__UpperCamelCase     ,					re.IGNORECASE     )
            if start_token is None:
                break
            _UpperCAmelCase          =   start_token.group(1     )
            _UpperCAmelCase          =   re.search(rf"""</s_{key}>"""     ,					__UpperCamelCase     ,					re.IGNORECASE     )
            _UpperCAmelCase          =   start_token.group()
            if end_token is None:
                _UpperCAmelCase          =   tokens.replace(__UpperCamelCase     ,					""""""     )
            else:
                _UpperCAmelCase          =   end_token.group()
                _UpperCAmelCase          =   re.escape(__UpperCamelCase     )
                _UpperCAmelCase          =   re.escape(__UpperCamelCase     )
                _UpperCAmelCase          =   re.search(f"""{start_token_escaped}(.*?){end_token_escaped}"""     ,					__UpperCamelCase     ,					re.IGNORECASE     )
                if content is not None:
                    _UpperCAmelCase          =   content.group(1     ).strip()
                    if r"<s_" in content and r"</s_" in content:  # non-leaf node
                        _UpperCAmelCase          =   self.tokenajson(__UpperCamelCase     ,					is_inner_value=__UpperCamelCase     ,					added_vocab=__UpperCamelCase     )
                        if value:
                            if len(__UpperCamelCase     ) == 1:
                                _UpperCAmelCase          =   value[0]
                            _UpperCAmelCase          =   value
                    else:  # leaf nodes
                        _UpperCAmelCase          =   []
                        for leaf in content.split(r"""<sep/>"""     ):
                            _UpperCAmelCase          =   leaf.strip()
                            if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                _UpperCAmelCase          =   leaf[1:-2]  # for categorical special tokens
                            output[key].append(__UpperCamelCase     )
                        if len(output[key]     ) == 1:
                            _UpperCAmelCase          =   output[key][0]

                _UpperCAmelCase          =   tokens[tokens.find(__UpperCamelCase     ) + len(__UpperCamelCase     ) :].strip()
                if tokens[:6] == r"<sep/>":  # non-leaf nodes
                    return [output] + self.tokenajson(tokens[6:]     ,					is_inner_value=__UpperCamelCase     ,					added_vocab=__UpperCamelCase     )

        if len(__UpperCamelCase     ):
            return [output] if is_inner_value else output
        else:
            return [] if is_inner_value else {"text_sequence": tokens}







    @property
    def      _snake_case					(			self			:       Tuple     )		->Optional[int]:






        '''simple docstring'''






        warnings.warn(
            """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""     ,					__UpperCamelCase     ,					)
        return self.image_processor_class







    @property
    def      _snake_case					(			self			:       List[str]     )		->Dict:






        '''simple docstring'''






        warnings.warn(
            """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""     ,					__UpperCamelCase     ,					)
        return self.image_processor