a
    h73                     @   sz   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 e
eZdd	d
Zdd ZG dd deZdgZdS )z Tokenization classes for PhoBERT    N)copyfile)Optional   )PreTrainedTokenizer)loggingz	vocab.txtz	bpe.codes)
vocab_filemerges_filec                 C   s>   t  }| d }| dd D ]}|||f |}qt |}|S )z
    Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    r      N)setadd)wordpairsZ	prev_charchar r   l/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/phobert/tokenization_phobert.py	get_pairs#   s    r   c                       s   e Zd ZdZeZd& f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dd Zdd Zdd Zdd Zdd  Zd*ee	e ee d!d"d#Zd$d% Z  ZS )+PhobertTokenizeraO	  
    Construct a PhoBERT tokenizer. Based on Byte-Pair-Encoding.

    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.
        merges_file (`str`):
            Path to the merges file.
        bos_token (`st`, *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.
    <s></s><unk><pad><mask>c
              
      s   || _ || _i | _d| jt|< d| jt|< d| jt|< d| jt|< | | dd | j D | _t|dd&}| 	d	d d
 }W d    n1 s0    Y  dd |D }t
t|tt|| _i | _t jf |||||||	d|
 d S )Nr   r	      r   c                 S   s   i | ]\}}||qS r   r   ).0kvr   r   r   
<dictcomp>~       z-PhobertTokenizer.__init__.<locals>.<dictcomp>utf-8encoding
c                 S   s    g | ]}t | d d qS )Nr"   )tuplesplit)r   merger   r   r   
<listcomp>   r   z-PhobertTokenizer.__init__.<locals>.<listcomp>)	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_token)r   r   encoderstradd_from_fileitemsdecoderopenreadr$   dictziprangelen	bpe_rankscachesuper__init__)selfr   r   r'   r(   r*   r+   r)   r,   r-   kwargsZmerges_handleZmerges	__class__r   r   r<   f   s2    
4zPhobertTokenizer.__init__N)token_ids_0token_ids_1returnc                 C   sD   |du 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. A PhoBERT 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=   rA   rB   clssepr   r   r    build_inputs_with_special_tokens   s
    z1PhobertTokenizer.build_inputs_with_special_tokensF)rA   rB   already_has_special_tokensrC   c                    sh   |rt  j||ddS |du 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)rA   rB   rI   Nr	   r   )r;   get_special_tokens_maskr8   )r=   rA   rB   rI   r?   r   r   rJ      s    z(PhobertTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|du 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. PhoBERT 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   )rE   rD   r8   )r=   rA   rB   rG   rF   r   r   r   $create_token_type_ids_from_sequences   s
    z5PhobertTokenizer.create_token_type_ids_from_sequencesc                 C   s
   t | jS N)r8   r.   r=   r   r   r   
vocab_size   s    zPhobertTokenizer.vocab_sizec                 C   s   t | jfi | jS rL   )r5   r.   Zadded_tokens_encoderrM   r   r   r   	get_vocab   s    zPhobertTokenizer.get_vocabc           
         s  | j v r j | S t|}tt|d d |d d g }t|}|sN|S t| fddd}| jvrpql|\}}g }d}|t|k rBz|||}	W n* ty   |	||d   Y qBY n0 |	|||	  |	}|| |kr*|t|d k r*||d  |kr*|
||  |d7 }q|
||  |d7 }qt|}|}t|dkrbqlqNt|}qNd	|}|d d
 }| j |< |S )Nr"   z</w>c                    s    j | tdS )Ninf)r9   getfloat)pairrM   r   r   <lambda>   r   z&PhobertTokenizer.bpe.<locals>.<lambda>)keyr   r	   r   @@ )r:   r#   listr   minr9   r8   index
ValueErrorextendappendjoin)
r=   tokenr   r   ZbigramfirstsecondZnew_wordijr   rM   r   bpe   sF    

"
2




zPhobertTokenizer.bpec                 C   s8   g }t d|}|D ]}|t| |d q|S )zTokenize a string.z\S+\n? )refindallr\   rX   rd   r$   )r=   textZsplit_tokenswordsr_   r   r   r   	_tokenize  s
    zPhobertTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r.   rQ   r)   )r=   r_   r   r   r   _convert_token_to_id  s    z%PhobertTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)r2   rQ   r)   )r=   rZ   r   r   r   _convert_id_to_token!  s    z%PhobertTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string.re   rV    )r^   replacestrip)r=   tokensZ
out_stringr   r   r   convert_tokens_to_string%  s    z)PhobertTokenizer.convert_tokens_to_string)save_directoryfilename_prefixrC   c                 C   s  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| nLt j	| jst|d$}| j }|| W d    n1 s0    Y  t j| jt j|krt
| j| ||fS )NzVocabulary path (z) should be a directory-rm   r   r   wb)ospathisdirloggererrorr^   VOCAB_FILES_NAMESabspathr   isfiler   r3   Zsp_modelZserialized_model_protowriter   )r=   rr   rs   Zout_vocab_fileZout_merge_filefiZcontent_spiece_modelr   r   r   save_vocabulary*  s$    (
(z PhobertTokenizer.save_vocabularyc           	   
   C   s   t |trz<t|ddd}| | W d   n1 s:0    Y  W nH tyn } z|W Y d}~n*d}~0  ty   td| dY n0 dS | }|D ]B}| }|	d}|dkrt
d	|d| }t| j| j|< qdS )
zi
        Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
        rr   r   NzIncorrect encoding detected in z, please rebuild the datasetre   r"   z5Incorrect dictionary format, expected '<token> <cnt>')
isinstancer/   r3   r0   FileNotFoundErrorUnicodeError	Exception	readlinesro   rfindr[   r8   r.   )	r=   ffdZfnfelinesZlineTmplineidxr   r   r   r   r0   G  s"    
,
zPhobertTokenizer.add_from_file)r   r   r   r   r   r   r   )N)NF)N)N)__name__
__module____qualname____doc__r{   Zvocab_files_namesr<   rX   intr   rH   boolrJ   rK   propertyrN   rO   rd   rj   rk   rl   rq   r/   r#   r   r0   __classcell__r   r   r?   r   r   3   sF   0       -   
,
r   )r   rv   rf   shutilr   typingr   Ztokenization_utilsr   utilsr   Z
get_loggerr   ry   r{   r   r   __all__r   r   r   r   <module>   s   
  .