U
    9%e;                     @   s   d Z ddl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mZ eeZdd	iZdd
diiZG dd deZdS )zTokenization classes.    N)copyfile)AnyDictListOptionalTuple   )
AddedTokenPreTrainedTokenizer)SPIECE_UNDERLINElogging
vocab_filezspiece.modelzTsinghuaAI/CPM-GeneratezHhttps://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.modelc                       sL  e Zd ZdZeZeZddddddddd	d
ddgdfee	e
ef  dd fddZedd Zdd Zdd Zdd Zdd Ze
ee
 dddZdd Zd d! Zd"d# Zd1ee eee  ee d$d%d&Zd2ee eee  eee d' fd(d)Zd3ee eee  ee d$d*d+Zd4e
ee
 ee
 d,d-d.Z fd/d0Z  Z S )5CpmTokenizerzMRuns pre-tokenization with Jieba segmentation tool. It is used in CPM models.FTz<s>z</s>z<unk>z<sep>z<pad>z<cls>z<mask>z<eop>z<eod>N)sp_model_kwargsreturnc                    s   t |trt|dddn|}|dkr(i n|| _|| _|| _|| _|| _tj	f | j| _
| j
| zddl}W n, tk
r } z|dW 5 d}~X Y nX || _tdd| _t jf ||||||||	|
||| jd	| d
| _dS )a  
        Construct a CPM tokenizer. Based on [Jieba](https://pypi.org/project/jieba/) and
        [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`):
                [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
                contains the vocabulary necessary to instantiate a tokenizer.
            do_lower_case (`bool`, *optional*, defaults to `True`):
                Whether to lowercase the input when tokenizing.
            remove_space (`bool`, *optional*, defaults to `True`):
                Whether to strip the text when tokenizing (removing excess spaces before and after the string).
            keep_accents (`bool`, *optional*, defaults to `False`):
                Whether to keep accents when tokenizing.
            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>

            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.
            sep_token (`str`, *optional*, defaults to `"<sep>"`):
                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.
            pad_token (`str`, *optional*, defaults to `"<pad>"`):
                The token used for padding, for example when batching sequences of different lengths.
            cls_token (`str`, *optional*, defaults to `"<cls>"`):
                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.
            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.
            additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
                Additional special tokens used by the tokenizer.

        Attributes:
            sp_model (`SentencePieceProcessor`):
                The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
        TF)lstriprstripNr   zxYou need to install jieba to use CpmTokenizer or CpmTokenizerFast. See https://pypi.org/project/jieba/ for installation.z 
u   ▂▃)do_lower_caseremove_spacekeep_accents	bos_token	eos_token	unk_token	sep_token	pad_token	cls_token
mask_tokenadditional_special_tokensr   r   )
isinstancestrr	   r   r   r   r   r   spmSentencePieceProcessorsp_modelLoadjiebaModuleNotFoundError	__class__	maketransZ
translatorsuper__init__Z_pad_token_type_id)selfr   r   r   r   r   r   r   r   r   r   r   r   r   kwargsr$   errorr&    g/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/cpm/tokenization_cpm.pyr)   ,   sB    OzCpmTokenizer.__init__c                 C   s
   t | jS )N)lenr"   r*   r.   r.   r/   
vocab_size   s    zCpmTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r.   )Zconvert_ids_to_tokens).0ir1   r.   r/   
<dictcomp>   s      z*CpmTokenizer.get_vocab.<locals>.<dictcomp>)ranger2   updateZadded_tokens_encoder)r*   Zvocabr.   r1   r/   	get_vocab   s    zCpmTokenizer.get_vocabc                 C   s   | j  }d |d< |S )Nr"   )__dict__copy)r*   stater.   r.   r/   __getstate__   s    
zCpmTokenizer.__getstate__c                 C   s8   || _ t| dsi | _tjf | j| _| j| j d S )Nr   )r9   hasattrr   r    r!   r"   r#   r   )r*   dr.   r.   r/   __setstate__   s
    
zCpmTokenizer.__setstate__c                 C   sj   | j rd|  }n|}|dddd}| jsXtd|}ddd |D }| jrf|	 }|S )	N z``"z''ZNFKD c                 S   s   g | ]}t |s|qS r.   )unicodedata	combining)r3   cr.   r.   r/   
<listcomp>   s     
 z0CpmTokenizer.preprocess_text.<locals>.<listcomp>)
r   joinstripsplitreplacer   rC   	normalizer   lower)r*   inputsoutputsr.   r.   r/   preprocess_text   s    zCpmTokenizer.preprocess_text)textr   c                 C   s   |  |}| jj|td}g }|D ]}t|dkr|d tdkr|d  r| j|dd td}|d tkr|d d tkrt|d dkr|dd }n|d dd |d< |	|d  |
| q"|	| q"|S )	zTokenize a string.)Zout_type   ,NrB   r   )rO   r"   encoder   r0   isdigitZEncodeAsPiecesrJ   r   appendextend)r*   rP   piecesZ
new_piecesZpieceZ
cur_piecesr.   r.   r/   	_tokenize   s    
(zCpmTokenizer._tokenizec                 C   s   | j |S )z0Converts a token (str) in an id using the vocab.)r"   Z	PieceToId)r*   tokenr.   r.   r/   _convert_token_to_id   s    z!CpmTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)r"   Z	IdToPiece)r*   indexr.   r.   r/   _convert_id_to_token   s    z!CpmTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.rB   r@   )rG   rJ   r   rH   )r*   tokensZ
out_stringr.   r.   r/   convert_tokens_to_string   s    z%CpmTokenizer.convert_tokens_to_string)token_ids_0token_ids_1r   c                 C   s8   | j g}| jg}|dkr$|| | S || | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. An XLNet sequence has the following format:

        - single sequence: `X <sep> <cls>`
        - pair of sequences: `A <sep> B <sep> <cls>`

        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)sep_token_idZcls_token_id)r*   ra   rb   sepclsr.   r.   r/    build_inputs_with_special_tokens   s
    z-CpmTokenizer.build_inputs_with_special_tokens)ra   rb   already_has_special_tokensr   c                    s^   |rt  j||ddS |dk	rHdgt| dg dgt|  ddg S dgt| d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   rg   Nr   rQ   )r(   get_special_tokens_maskr0   )r*   ra   rb   rg   r-   r.   r/   rh     s      *z$CpmTokenizer.get_special_tokens_maskc                 C   sT   | j g}dg}|dkr,t|| dg | S t|| dg t|| dg  | S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
        sequence pair mask has the following format:

        ```
        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
        | first sequence    | second sequence |
        ```

        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

        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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
           Nr   rQ   )rc   r0   )r*   ra   rb   rd   Zcls_segment_idr.   r.   r/   $create_token_type_ids_from_sequences,  s
    z1CpmTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixr   c              	   C   s   t j|s"td| d d S t j||r6|d ndtd  }t j| jt j|krzt j	| jrzt
| j| n8t j	| jst|d}| j }|| W 5 Q R X |fS )NzVocabulary path (z) should be a directory-rB   r   wb)ospathisdirloggerr,   rG   VOCAB_FILES_NAMESabspathr   isfiler   openr"   Zserialized_model_protowrite)r*   rk   rl   Zout_vocab_filefiZcontent_spiece_modelr.   r.   r/   save_vocabularyK  s     (
zCpmTokenizer.save_vocabularyc                    s.   t  j||}|dddddd}|S )Nr@   rB   u   ▂u   ▃
)r(   _decoderJ   )r*   argsr+   rP   r-   r.   r/   r{   \  s    zCpmTokenizer._decode)N)NF)N)N)!__name__
__module____qualname____doc__rs   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapr   r   r   r   r)   propertyr2   r8   r<   r?   rO   r   rZ   r\   r^   r`   intrf   boolrh   rj   r   ry   r{   __classcell__r.   r.   r-   r/   r   &   sf   w
  
    
   
r   )r   ro   rC   shutilr   typingr   r   r   r   r   Zsentencepiecer    Ztokenization_utilsr	   r
   utilsr   r   Z
get_loggerr}   rr   rs   r   r   r.   r.   r.   r/   <module>   s   
 