U
    9%e]                     @   s   d Z ddlZddlZddlZddlZddlmZmZmZ ddl	m
Z
 ddlmZ eeZddd	Zd
dddddddddd	ZdddddZddiddiddiddidZdd Zdd Zdd Zdd ZG dd  d e
ZdS )!z"Tokenization classes for Flaubert.    N)ListOptionalTuple   )PreTrainedTokenizer)loggingz
vocab.jsonz
merges.txt)
vocab_filemerges_filezLhttps://huggingface.co/flaubert/flaubert_small_cased/resolve/main/vocab.jsonzMhttps://huggingface.co/flaubert/flaubert_base_uncased/resolve/main/vocab.jsonzKhttps://huggingface.co/flaubert/flaubert_base_cased/resolve/main/vocab.jsonzLhttps://huggingface.co/flaubert/flaubert_large_cased/resolve/main/vocab.json)zflaubert/flaubert_small_casedzflaubert/flaubert_base_uncasedzflaubert/flaubert_base_casedzflaubert/flaubert_large_casedzLhttps://huggingface.co/flaubert/flaubert_small_cased/resolve/main/merges.txtzMhttps://huggingface.co/flaubert/flaubert_base_uncased/resolve/main/merges.txtzKhttps://huggingface.co/flaubert/flaubert_base_cased/resolve/main/merges.txtzLhttps://huggingface.co/flaubert/flaubert_large_cased/resolve/main/merges.txti   do_lowercaseFTc                 C   s   ddd}|| dddS )zQ
    Converts `text` to Unicode (if it's not already), assuming UTF-8 input.
    utf-8strictc                 S   s<   t | tr| ||S t | tr$| S tdt|  dd S )Nznot expecting type '')
isinstancebytesdecodestr	TypeErrortype)sencodingerrors r   q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/flaubert/tokenization_flaubert.pyensure_textR   s
    

z'convert_to_unicode.<locals>.ensure_textignore)r   r   )r   r   r   )textr   r   r   r   convert_to_unicodeM   s    
r   c                 C   s6   t  }| d }| dd D ]}|||f |}q|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charr   r   r   	get_pairs^   s    r#   c                 C   s  |  dd} tdd| } |  dd} |  dd} |  dd} |  d	d
} |  dd
} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  dd} |  d d!} |  d"d#} |  d$d%} |  d&d'} |  d(d)} |  d*d+} |  d,d-} td.d| } |  d/d0} |  d1d2} |  d3d4} |  d5d6} |  d7d8} |  d9d:} |  d;d<} |  d=d>} |  d?d@} | S )Azz
    Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
    u   ，,u   。\s*z. u   、u   ”"u   “u   ∶:u   ：u   ？?u   《u   》u   ）)u   ！!u   （(u   ；;u   １1u   」u   「u   ０0u   ３3u   ２2u   ５5u   ６6u   ９9u   ７7u   ８8u   ４4u   ．\s*u   ～~u   ’r   u   …z...u   ━-u   〈<u   〉>u   【[u   】]u   ％%)replaceresub)r   r   r   r   replace_unicode_punctl   sJ    r@   c                 C   s8   g }| D ]$}t |}|dr"q|| qd|S )zw
    Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
    C )unicodedatacategory
startswithappendjoin)r   outputr"   catr   r   r   remove_non_printing_char   s    

rJ   c                       sj  e Zd ZdZeZeZeZ	e
Zdddddddddd	d
ddddddg
ddf
 fdd	Zedd Zdd Zdd Zdd Zdd Zedd Zd d! Zd"d# Zd$d% Zd=d&d'Zd(d) Zd*d+ Zd,d- Zd>ee eee  ee d.d/d0Zd?ee eee  eee d1 fd2d3Z d@ee eee  ee d.d4d5Z!dAe"ee" e#e" d6d7d8Z$d9d: Z%d;d< Z&  Z'S )BFlaubertTokenizera  
    Construct a Flaubert tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:

    - Moses preprocessing and tokenization.
    - Normalizing all inputs text.
    - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
      "__classify__") to a vocabulary.
    - The argument `do_lowercase` controls lower casing (automatically set for pretrained vocabularies).

    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`):
            Vocabulary file.
        merges_file (`str`):
            Merges file.
        do_lowercase (`bool`, *optional*, defaults to `False`):
            Controls lower casing.
        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.
        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>

        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.
        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 `"</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.
        mask_token (`str`, *optional*, defaults to `"<special1>"`):
            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 `["<special0>","<special1>","<special2>","<special3>","<special4>","<special5>","<special6>","<special7>","<special8>","<special9>"]`):
            List of additional special tokens.
        lang2id (`Dict[str, int]`, *optional*):
            Dictionary mapping languages string identifiers to their IDs.
        id2lang (`Dict[int, str]`, *optional*):
            Dictionary mapping language IDs to their string identifiers.
    Fz<unk>z<s>z</s>z<pad>z
<special1>z
<special0>z
<special2>z
<special3>z
<special4>z
<special5>z
<special6>z
<special7>z
<special8>z
<special9>Nc                    sl  | dd }|d k	rtd d| _|| _zdd l}W n tk
rR   tdY nX || _i | _i | _	dddh| _
|| _|| _|d k	r|d k	rt|t|kstd | _d | _t|d	d
}t|| _W 5 Q R X dd | j D | _t|d	d
}| dd d }W 5 Q R X dd |D }tt|tt|| _i | _t jf ||||||	|
||d	| d S )Ndo_lowercase_and_remove_accentz`do_lowercase_and_remove_accent` is passed as a keyword argument, but this won't do anything. `FlaubertTokenizer` will always set it to `False`.Fr   zsYou need to install sacremoses to use FlaubertTokenizer. See https://pypi.org/project/sacremoses/ for installation.zhthjar   r   c                 S   s   i | ]\}}||qS r   r   ).0kvr   r   r   
<dictcomp>  s      z.FlaubertTokenizer.__init__.<locals>.<dictcomp>
c                 S   s    g | ]}t | d d qS )N   )tuplesplit)rQ   merger   r   r   
<listcomp>!  s     z.FlaubertTokenizer.__init__.<locals>.<listcomp>)		unk_token	bos_token	sep_token	pad_token	cls_token
mask_tokenadditional_special_tokenslang2idid2lang) poploggerwarningrL   r
   
sacremosesImportErrorsmcache_moses_punct_normalizercache_moses_tokenizerZlang_with_custom_tokenizerrc   rd   lenAssertionErrorja_word_tokenizerZzh_word_tokenizeropenjsonloadencoderitemsdecoderreadrY   dictziprange	bpe_rankscachesuper__init__)selfr   r	   r
   r\   r]   r^   r_   r`   ra   rb   rc   rd   kwargsrL   rh   Zvocab_handleZmerges_handleZmerges	__class__r   r   r}      sX    
 
zFlaubertTokenizer.__init__c                 C   s   | j S N)rL   r~   r   r   r   do_lower_case2  s    zFlaubertTokenizer.do_lower_casec                 C   s8   || j kr$| jj|d}|| j |< n
| j | }||S )Nlang)rk   rj   ZMosesPunctNormalizer	normalize)r~   r   r   Zpunct_normalizerr   r   r   moses_punct_norm8  s
    

z"FlaubertTokenizer.moses_punct_normc                 C   s>   || j kr$| jj|d}|| j |< n
| j | }|j|dddS )Nr   F)Z
return_strescape)rl   rj   ZMosesTokenizertokenize)r~   r   r   Zmoses_tokenizerr   r   r   moses_tokenizeA  s
    

z FlaubertTokenizer.moses_tokenizec                 C   s    t |}| ||}t|}|S r   )r@   r   rJ   )r~   r   r   r   r   r   moses_pipelineJ  s    z FlaubertTokenizer.moses_pipelinec              	   C   s   | j d krz(dd l}|dtjd d| _ W nV ttfk
r   td td td td td	 td
  Y nX t	| j 
|S )Nr   z-model r6   z/local/share/kytea/model.binzMake sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper (https://github.com/chezou/Mykytea-python) with the following stepsz81. git clone git@github.com:neubig/kytea.git && cd kyteaz2. autoreconf -iz#3. ./configure --prefix=$HOME/localz4. make && make installz5. pip install kytea)ro   Mykyteaospath
expanduserAttributeErrorri   rf   errorlistZgetWS)r~   r   r   r   r   r   ja_tokenizeQ  s"    






zFlaubertTokenizer.ja_tokenizec                 C   s
   t | jS r   )rm   rs   r   r   r   r   
vocab_sizef  s    zFlaubertTokenizer.vocab_sizec                 C   s   t | jf| jS r   )rw   rs   Zadded_tokens_encoderr   r   r   r   	get_vocabl  s    zFlaubertTokenizer.get_vocabc           
         s  t |d d |d d f }| jkr2 j| S t|}|sF|d S t| fddd}| jkrhqf|\}}g }d}|t|k r<z|||}	W n, tk
r   |||d   Y q<Y nX ||||	  |	}|| |kr$|t|d k r$||d  |kr$|	||  |d7 }qx|	||  |d7 }qxt |}|}t|dkr\qfqFt|}qFd	
|}|d
kr~d}| j|< |S )NrV   </w>c                    s    j | tdS )Ninf)rz   getfloat)pairr   r   r   <lambda>z      z'FlaubertTokenizer.bpe.<locals>.<lambda>keyr   r   rW    z
  </w>z
</w>)rX   r{   r#   minrz   rm   index
ValueErrorextendrF   rG   )
r~   tokenr    r!   ZbigramfirstsecondZnew_wordijr   r   r   bpep  sF    


2





zFlaubertTokenizer.bpec                 C   s:   | dd dd}t|}td|}| jr6| }|S )Nz``r%   z''NFC)r=   r   rC   r   r
   lower)r~   r   r   r   r   preprocess_text  s    z!FlaubertTokenizer.preprocess_textc                 C   s   d}|r"| j r"|| j kr"td |r0| }n&| |}| j||d}| j||d}g }|D ]"}|r^|t| 	|d q^|S )a  
        Tokenize a string given language code using Moses.

        Details of tokenization:

            - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
            - Install with `pip install sacremoses`

        Args:
            - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
              (bool). If True, we only apply BPE.

        Returns:
            List of tokens.
        frzSupplied language code not found in lang2id mapping. Please check that your language is supported by the loaded pretrained model.r   r   )
rc   rf   r   rY   r   r   r   r   r   r   )r~   r   Zbypass_tokenizerr   Zsplit_tokensr   r   r   r   	_tokenize  s    

zFlaubertTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rs   r   r\   )r~   r   r   r   r   _convert_token_to_id  s    z&FlaubertTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)ru   r   r\   )r~   r   r   r   r   _convert_id_to_token  s    z&FlaubertTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string.rB   r   r   )rG   r=   strip)r~   tokensZ
out_stringr   r   r   convert_tokens_to_string  s    z*FlaubertTokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 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 XLM sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </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)Zbos_token_idsep_token_id)r~   r   r   Zbossepr   r   r    build_inputs_with_special_tokens  s
    z2FlaubertTokenizer.build_inputs_with_special_tokens)r   r   already_has_special_tokensr   c                    sf   |rt  j||ddS |dk	rLdgdgt|  dg dgt|  dg S 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)r   r   r   Nr   r   )r|   get_special_tokens_maskrm   )r~   r   r   r   r   r   r   r     s      .z)FlaubertTokenizer.get_special_tokens_maskc                 C   sV   | j g}| j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 XLM 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   r   )r   Zcls_token_idrm   )r~   r   r   r   clsr   r   r   $create_token_type_ids_from_sequences  s
    z6FlaubertTokenizer.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||rX|d ndtd  }t|ddd	$}|t	j
| jd
dddd  W 5 Q R X d}t|ddd	`}t| j dd dD ]B\}}	||	krtd| d |	}|d|d  |d7 }qW 5 Q R X ||fS )NzVocabulary path (z) should be a directoryr7   rB   r   r	   wr   rP   rW   TF)indent	sort_keysensure_asciirU   r   c                 S   s   | d S )Nr   r   )kvr   r   r   r   C  r   z3FlaubertTokenizer.save_vocabulary.<locals>.<lambda>r   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!r   r   )r   r   isdirrf   r   rG   VOCAB_FILES_NAMESrp   writerq   dumpsrs   sortedrz   rt   rg   )
r~   r   r   r   Z
merge_filefr   writerZ
bpe_tokensZtoken_indexr   r   r   save_vocabulary3  s0      (
z!FlaubertTokenizer.save_vocabularyc                 C   s   | j  }d |d< |S )Nrj   )__dict__copy)r~   stater   r   r   __getstate__P  s    
zFlaubertTokenizer.__getstate__c                 C   s:   || _ zdd l}W n tk
r.   tdY nX || _d S )Nr   znYou need to install sacremoses to use XLMTokenizer. See https://pypi.org/project/sacremoses/ for installation.)r   rh   ri   rj   )r~   drh   r   r   r   __setstate__V  s    
zFlaubertTokenizer.__setstate__)F)N)NF)N)N)(__name__
__module____qualname____doc__r   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapPRETRAINED_INIT_CONFIGURATIONZpretrained_init_configuration&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesr}   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   intr   r   boolr   r   r   r   r   r   r   __classcell__r   r   r   r   rK      s   4S
		
,

&  
    
   
rK   )r   rq   r   r>   rC   typingr   r   r   Ztokenization_utilsr   utilsr   Z
get_loggerr   rf   r   r   r   r   r   r#   r@   rJ   rK   r   r   r   r   <module>   sJ   
,