U
    4Af4                     @   s   d Z ddlZddlmZ ddlmZmZmZmZm	Z	 ddl
ZddlmZmZ ddlmZ eeZdZd	d
dZG dd deZdS )z0Tokenization classes for BARTpho-syllable model.    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenPreTrainedTokenizer)loggingu   ▁zsentencepiece.bpe.modelzdict.txt)
vocab_filemonolingual_vocab_filec                       s   e Zd ZdZeZddgZd*eee	e
f  d	d
 fddZdd Zdd Zd+ee eee  ee dddZd,ee eee  eee d fddZd-ee eee  ee dddZedd Zdd Ze	ee	 ddd Zd!d" Zd#d$ Zd%d& Zd.e	ee	 ee	 d'd(d)Z  ZS )/BartphoTokenizera  
    Adapted from [`XLMRobertaTokenizer`]. Based on [SentencePiece](https://github.com/google/sentencepiece).

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file. This vocabulary is the pre-trained SentencePiece model available from the
            multilingual XLM-RoBERTa, also used in mBART, consisting of 250K types.
        monolingual_vocab_file (`str`):
            Path to the monolingual vocabulary file. This monolingual vocabulary consists of Vietnamese-specialized
            types extracted from the multilingual vocabulary vocab_file of 250K types.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        unk_token (`str`, *optional*, defaults to `"<unk>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        mask_token (`str`, *optional*, defaults to `"<mask>"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

            - `enable_sampling`: Enable subword regularization.
            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.

    Attributes:
        sp_model (`SentencePieceProcessor`):
            The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
    Z	input_idsZattention_mask<s></s><unk><pad><mask>N)sp_model_kwargsreturnc                    sJ  t |	trt|	dddn|	}	|
d kr(i n|
| _|| _|| _tjf | j| _| j	t| i | _
d}||||||fD ](}t|| j
krt|| j
t|< |d7 }qtt|ddd4}| D ]$}|  d }t| j
| j
|< qW 5 Q R X t|	| j
kr
t| j
| j
t|	< d	d
 | j
 D | _t jf |||||||	| jd| d S )NTF)lstriprstripr      rutf-8encodingc                 S   s   i | ]\}}||qS  r   ).0kvr   r   T/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/bartpho/tokenization_bartpho.py
<dictcomp>   s      z-BartphoTokenizer.__init__.<locals>.<dictcomp>)	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenr   )
isinstancestrr	   r   r   r   spmSentencePieceProcessorsp_modelLoadfairseq_tokens_to_idsopen	readlinesstripsplitlenitemsfairseq_ids_to_tokenssuper__init__)selfr   r   r#   r$   r&   r'   r%   r(   r)   r   kwargsZcnttokenfline	__class__r   r!   r9   k   s>    
	zBartphoTokenizer.__init__c                 C   s$   | j  }d |d< | j |d< |S )Nr.   sp_model_proto)__dict__copyr.   serialized_model_proto)r:   stater   r   r!   __getstate__   s    
zBartphoTokenizer.__getstate__c                 C   s8   || _ t| dsi | _tjf | j| _| j| j d S )Nr   )rB   hasattrr   r,   r-   r.   ZLoadFromSerializedProtorA   )r:   dr   r   r!   __setstate__   s
    
zBartphoTokenizer.__setstate__)token_ids_0token_ids_1r   c                 C   sD   |dkr| j g| | jg S | j g}| jg}|| | | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An BARTPho sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </s></s> B </s>`

        Args:
            token_ids_0 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        N)cls_token_idsep_token_id)r:   rJ   rK   clssepr   r   r!    build_inputs_with_special_tokens   s
    z1BartphoTokenizer.build_inputs_with_special_tokensF)rJ   rK   already_has_special_tokensr   c                    sh   |rt  j||ddS |dkr8dgdgt|  dg S dgdgt|  ddg dgt|  dg S )a  
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)rJ   rK   rQ   Nr   r   )r8   get_special_tokens_maskr5   )r:   rJ   rK   rQ   r?   r   r!   rR      s      z(BartphoTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|dkr.t|| | dg S t|| | | | | dg S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. BARTPho does not
        make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.

        Nr   )rM   rL   r5   )r:   rJ   rK   rO   rN   r   r   r!   $create_token_type_ids_from_sequences   s
    z5BartphoTokenizer.create_token_type_ids_from_sequencesc                 C   s
   t | jS )N)r5   r7   r:   r   r   r!   
vocab_size   s    zBartphoTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r   )Zconvert_ids_to_tokens)r   irT   r   r!   r"     s      z.BartphoTokenizer.get_vocab.<locals>.<dictcomp>)rangerU   updateZadded_tokens_encoder)r:   Zvocabr   rT   r!   	get_vocab  s    zBartphoTokenizer.get_vocab)textr   c                 C   s   | j j|tdS )N)Zout_type)r.   encoder+   )r:   rZ   r   r   r!   	_tokenize	  s    zBartphoTokenizer._tokenizec                 C   s   || j kr| j | S | jS dS )z0Converts a token (str) in an id using the vocab.N)r0   Zunk_token_id)r:   r<   r   r   r!   _convert_token_to_id  s    

z%BartphoTokenizer._convert_token_to_idc                 C   s
   | j | S )z=Converts an index (integer) in a token (str) using the vocab.)r7   )r:   indexr   r   r!   _convert_id_to_token  s    z%BartphoTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.  )joinreplaceSPIECE_UNDERLINEr3   )r:   tokensZ
out_stringr   r   r!   convert_tokens_to_string  s    z)BartphoTokenizer.convert_tokens_to_string)save_directoryfilename_prefixr   c           	   	   C   sn  t j|s"td| d d S t j||r6|d ndtd  }t j||rX|d ndtd  }t j| jt j|krt j	| jrt
| j| n8t j	| jst|d}| j }|| W 5 Q R X t j| jt j|krt j	| jrt
| j| nXt j	| jsft|dd	d
4}| jD ]&}|| jkr4|t| d q4W 5 Q R X ||fS )NzVocabulary path (z) should be a directory-r`   r   r   wbwr   r   z 
)ospathisdirloggererrorrb   VOCAB_FILES_NAMESabspathr   isfiler   r1   r.   rD   writer   r0   Zall_special_tokensr+   )	r:   rg   rh   Zout_vocab_fileZout_monolingual_vocab_filefiZcontent_spiece_modelfpr<   r   r   r!   save_vocabulary  s:     (

"z BartphoTokenizer.save_vocabulary)r   r   r   r   r   r   r   N)N)NF)N)N)__name__
__module____qualname____doc__rq   Zvocab_files_namesZmodel_input_namesr   r   r+   r   r9   rF   rI   r   intrP   boolrR   rS   propertyrU   rY   r\   r]   r_   rf   r   rw   __classcell__r   r   r?   r!   r   "   sZ   E        6  
    
   

r   )r{   rl   shutilr   typingr   r   r   r   r   Zsentencepiecer,   Ztokenization_utilsr	   r
   utilsr   Z
get_loggerrx   ro   rd   rq   r   r   r   r   r!   <module>   s   

