U
    &ºc“Š  ã                p   @   sö  d Z ddlZddlZddlZddlZddlZddlZddlmZm	Z	 ddl
ZddlmZ e e¡ZdddœZd	d
dddddddddœ
dddddddddddœ
dœZdddddddddddœ
Zddi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/d0d1d2d3d4œddd5d6d7d8d9d:d;d<d=d>d?d@dAdBœd#œdd(d)dd*d d+d$d,d-d.d/d0d1d2d3d4œddd5d6d7d8d9d:d;d<d=d>d?d@dAdBœd#œdd d$d!œddd%œd#œddd d!œddd"œd#œdCd(dd d+d$d,dDdEdFdGdHdId-dJd0d2d3dKœddd5d6d7d8d9d:d;d<d=d>d?d@dAdLdMdNœd#œdCdOdPdQdRdSd(dTdUdVdWdXd)dYdZd[d\d]d^d_d`dadd*d dbd+dcdddedfd$dgdhdidjdkdld,dmdndodpdqdrdDdEdsdtdudvdFdwdxdydzd{d|d}d~dd€dd‚dƒdGd„d…d†dHdId&d-d‡dˆd‰dŠd‹dŒddŽddJd.dd‘d/d’d0d“d”d1d•d2d–d—d˜d3d™dšd›dœœdddd5d6d7d8d9d:d;d<d=d>d?d@dAdLdMddž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Ð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ðœdd#œdœ
Zdñ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 XLM.é    N)ÚListÚOptionalé   )ÚPreTrainedTokenizerz
vocab.jsonz
merges.txt)Ú
vocab_fileÚmerges_filezNhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-en-2048-vocab.jsonzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-vocab.jsonzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-vocab.jsonzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enro-1024-vocab.jsonzVhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-tlm-xnli15-1024-vocab.jsonzRhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-xnli15-1024-vocab.jsonzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-enfr-1024-vocab.jsonzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-ende-1024-vocab.jsonzNhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-17-1280-vocab.jsonzOhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-100-1280-vocab.json)
zxlm-mlm-en-2048zxlm-mlm-ende-1024zxlm-mlm-enfr-1024zxlm-mlm-enro-1024zxlm-mlm-tlm-xnli15-1024zxlm-mlm-xnli15-1024zxlm-clm-enfr-1024zxlm-clm-ende-1024zxlm-mlm-17-1280zxlm-mlm-100-1280zNhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-en-2048-merges.txtzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-merges.txtzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-merges.txtzPhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enro-1024-merges.txtzVhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-tlm-xnli15-1024-merges.txtzRhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-xnli15-1024-merges.txtzNhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-17-1280-merges.txtzOhttps://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-100-1280-merges.txti   Údo_lowercase_and_remove_accentTÚdeÚen)Ú0Ú1)r	   r
   )r   Úid2langÚlang2idÚfr)r
   r   Úro)r
   r   ÚarÚbgÚelÚesÚhiÚruÚswÚthÚtrÚurÚviÚzh)r   r   Ú2Ú3Ú4Ú5Ú6Ú7Ú8Ú9Ú10Ú11Ú12Ú13Ú14é   é   é   é   é   é   é   é	   é
   é   é   é   é   )r   r   r	   r   r
   r   r   r   r   r   r   r   r   r   r   FÚitÚjaÚkoÚnlÚplÚptÚsv)r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   Ú15Ú16é   é   )r   r	   r
   r   r   r   r7   r8   r9   r:   r;   r<   r   r=   r   r   r   ÚafÚalsÚamÚanÚangÚarzÚastÚazÚbarÚbeÚbnÚbrÚbsÚcaÚcebÚckbÚcsÚcyÚdaÚeoÚetÚeuÚfaÚfiÚfyÚgaÚganÚglÚguÚheÚhrÚhuÚhyÚiaÚidÚisÚjvÚkaÚkkÚknÚkuÚlaÚlbÚltÚlvÚmkÚmlÚmnÚmrÚmsÚmyÚndsÚneÚnnÚnoÚocÚscnÚscoÚshÚsiÚsimpleÚskÚslÚsqÚsrÚtaÚteÚtlÚttÚukÚuzÚwarÚwuuÚyiÚzh_classicalÚ
zh_min_nanÚzh_yue)dr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r>   r?   Z17Z18Z19Z20Z21Z22Z23Z24Z25Z26Z27Z28Z29Z30Z31Z32Z33Z34Z35Z36Z37Z38Z39Z40Z41Z42Z43Z44Z45Z46Z47Z48Z49Z50Z51Z52Z53Z54Z55Z56Z57Z58Z59Z60Z61Z62Z63Z64Z65Z66Z67Z68Z69Z70Z71Z72Z73Z74Z75Z76Z77Z78Z79Ú80Z81Z82Z83Z84Z85Z86Z87Z88Z89Z90Z91Z92Z93Z94Z95Z96Z97Z98Z99é   é   é   é   é   é   é   é   é   é   é   é   é   é   é   é    é!   é"   é#   é$   é%   é&   é'   é(   é)   é*   é+   é,   é-   é.   é/   é0   é1   é2   é3   é4   é5   é6   é7   é8   é9   é:   é;   é<   é=   é>   é?   é@   éA   éB   éC   éD   éE   éF   éG   éH   éI   éJ   éK   éL   éM   éN   éO   éP   éQ   éR   éS   éT   éU   éV   éW   éX   éY   éZ   é[   é\   é]   é^   é_   é`   éa   éb   éc   )drB   rC   rD   rE   rF   r   rG   rH   rI   rJ   rK   r   rL   rM   rN   rO   rP   rQ   rR   rS   rT   r	   r   r
   rU   r   rV   rW   rX   rY   r   rZ   r[   r\   r]   r^   r_   r   r`   ra   rb   rc   rd   re   r7   r8   rf   rg   rh   ri   r9   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   r:   rw   rx   ry   r;   r<   r   r   rz   r{   r|   r}   r~   r   r€   r   r‚   r=   r   rƒ   r„   r   r…   r   r†   r‡   r   rˆ   r   r‰   rŠ   r‹   r   rŒ   r   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   r   N)ÚsetÚadd)ÚwordÚpairsZ	prev_charÚchar© rè   úA/tmp/pip-unpacked-wheel-ymerj3tt/transformers/tokenization_xlm.pyÚ	get_pairs®  s    rê   c                 C   s^   d  | ¡} |  ¡ } t d| ¡} g }| D ]"}t |¡}|dkr>q&| |¡ q&d  |¡ ¡  d¡S )z¡
    Lowercase and strips accents from a piece of text based on
    https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
    ú ZNFDZMnÚ )ÚjoinÚlowerÚunicodedataÚ	normalizeÚcategoryÚappendÚsplit©ÚtextÚoutputrç   Úcatrè   rè   ré   Úlowercase_and_remove_accent»  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   ï¼‘r   u   ã€u   ã€Œu   ï¼r   u   ï¼“r   u   ï¼’r   u   ï¼•r    u   ï¼–r!   u   ï¼™r$   u   ï¼—r"   u   ï¼˜r#   u   ï¼”r   u   ï¼Ž\s*u   ï½žú~u   â€™ú'u   â€¦z...u   â”ú-u   ã€ˆú<u   ã€‰ú>u   ã€ú[u   ã€‘ú]u   ï¼…ú%)ÚreplaceÚreÚsub©rõ   rè   rè   ré   Úreplace_unicode_punctÌ  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
    ÚCrì   )rï   rñ   Ú
startswithrò   rí   rô   rè   rè   ré   Úremove_non_printing_char÷  s    

r  c                 C   s   |   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¡} | S )zVSennrich's WMT16 scripts for Romanian preprocessing, used by model `xlm-mlm-enro-1024`u   Åžu   È˜u   ÅŸu   È™u   Å¢u   Èšu   Å£u   È›ÚSÚsÚTÚtu   Ä‚ÚAu   ÄƒÚaõ   Ã‚õ   Ã¢õ   ÃŽÚIõ   Ã®Úi)r	  r  rè   rè   ré   Úromanian_preprocessing  s    r  c                       s.  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g
dddf
‡ f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d6d$d%„Zd&d'„ Zd(d)„ Zd*d+„ Zd7ee eee  ee d,œd-d.„Zd8ee eee  eee d/œd0d1„Zd9ee eee  ee d,œd2d3„Zd4d5„ Z ‡  Z!S ):ÚXLMTokenizera-  
    BPE tokenizer for XLM

    - Moses preprocessing & tokenization for most supported languages
    - Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP)
    - (optionally) lower case & normalize all inputs text
    - argument ``special_tokens`` and function ``set_special_tokens``, can be used to add additional symbols       (ex: "__classify__") to a vocabulary
    - `lang2id` attribute maps the languages supported by the model with their ids if provided (automatically set for pretrained vocabularies)
    - `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies)

    This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
    should refer to the superclass for more information regarding methods.

    Args:
        vocab_file (:obj:`string`):
            Vocabulary file.
        merges_file (:obj:`string`):
            Merges file.
        do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to lowercase the input when tokenizing.
        remove_space (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to strip the text when tokenizing (removing excess spaces before and after the string).
        keep_accents (:obj:`bool`, `optional`, defaults to :obj:`False`):
            Whether to keep accents when tokenizing.
        unk_token (:obj:`string`, `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 (:obj:`string`, `optional`, defaults to "<s>"):
            The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.

            .. note::

                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 :obj:`cls_token`.
        sep_token (:obj:`string`, `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 (:obj:`string`, `optional`, defaults to "<pad>"):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (:obj:`string`, `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 (:obj:`string`, `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 (:obj:`List[str]`, `optional`, defaults to :obj:`["<special0>","<special1>","<special2>","<special3>","<special4>","<special5>","<special6>","<special7>","<special8>","<special9>"]`):
            List of additional special tokens.
        lang2id (:obj:`Dict[str, int]`, `optional`, defaults to :obj:`None`):
            Dictionary mapping languages string identifiers to their IDs.
        id2lang (:obj:`Dict[int, str`, `optional`, defaults to :obj:`None`):
            Dictionary mapping language IDs to their string identifiers.
        do_lowercase_and_remove_accent (:obj:`bool`, `optional`, defaults to :obj:`True`):
            Whether to lowercase and remove accents when tokenizing.
    z<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>NTc              
      s  t ƒ jf |||||||	dœ|—Ž tƒ | _tƒ | _tdddgƒ| _|| _|
| _|| _	|
d k	rx|d k	rxt
|
ƒt
|ƒksxt‚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 | _d S )N)Ú	unk_tokenÚ	bos_tokenÚ	sep_tokenÚ	pad_tokenÚ	cls_tokenÚ
mask_tokenÚadditional_special_tokensr   r   r8   úutf-8©Úencodingc                 S   s   i | ]\}}||“qS rè   rè   )Ú.0ÚkÚvrè   rè   ré   Ú
<dictcomp>‰  s      z)XLMTokenizer.__init__.<locals>.<dictcomp>Ú
éÿÿÿÿc                 S   s    g | ]}t | ¡ d d… ƒ‘qS )Nr*   )Útupleró   )r)  Úmergerè   rè   ré   Ú
<listcomp>Œ  s     z)XLMTokenizer.__init__.<locals>.<listcomp>)ÚsuperÚ__init__ÚdictÚcache_moses_punct_normalizerÚcache_moses_tokenizerrã   Úlang_with_custom_tokenizerr   r   r   ÚlenÚAssertionErrorÚja_word_tokenizerZzh_word_tokenizerÚopenÚjsonÚloadÚencoderÚitemsÚdecoderÚreadró   ÚzipÚrangeÚ	bpe_ranksÚcache)Úselfr   r   r  r   r!  r"  r#  r$  r%  r   r   r   ÚkwargsZvocab_handleZmerges_handleZmerges©Ú	__class__rè   ré   r3  R  s:    ùø zXLMTokenizer.__init__c                 C   s6   || j kr"tj|d}|| j |< n
| j | }| |¡S )N©Úlang)r5  ÚsmZMosesPunctNormalizerrð   )rF  rõ   rK  Zpunct_normalizerrè   rè   ré   Úmoses_punct_norm  s
    

zXLMTokenizer.moses_punct_normc                 C   s<   || j kr"tj|d}|| j |< n
| j | }|j|dddS )NrJ  F)Z
return_strÚescape)r6  rL  ZMosesTokenizerÚtokenize)rF  rõ   rK  Zmoses_tokenizerrè   rè   ré   Úmoses_tokenize˜  s
    

zXLMTokenizer.moses_tokenizec                 C   s    t |ƒ}|  ||¡}t|ƒ}|S ©N)r  rM  r  )rF  rõ   rK  rè   rè   ré   Úmoses_pipeline   s    zXLMTokenizer.moses_pipelinec              	   C   s–   | j d kr†z$dd l}| dtj 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 %s/local/share/kytea/model.binr  z™Make 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)r:  ÚMykyteaÚosÚpathÚ
expanduserÚAttributeErrorÚImportErrorÚloggerÚerrorÚlistZgetWS)rF  rõ   rS  rè   rè   ré   Úja_tokenize¦  s"    
ÿ
ÿ




zXLMTokenizer.ja_tokenizec                 C   s
   t | jƒS rQ  )r8  r>  ©rF  rè   rè   ré   Ú
vocab_sizeº  s    zXLMTokenizer.vocab_sizec                 C   s   t | jf| jŽS rQ  )r4  r>  Zadded_tokens_encoderr]  rè   rè   ré   Ú	get_vocab¾  s    zXLMTokenizer.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 )Nr.  ú</w>c                    s   ˆ j  | tdƒ¡S )NÚinf)rD  ÚgetÚfloat)Úpairr]  rè   ré   Ú<lambda>Ë  ó    z"XLMTokenizer.bpe.<locals>.<lambda>©Úkeyr   r   r*   rë   z
  </w>z
</w>)r/  rE  rê   ÚminrD  r8  ÚindexÚ
ValueErrorÚextendrò   rí   )
rF  Útokenrå   ræ   ZbigramÚfirstÚsecondZnew_wordr  Újrè   r]  ré   ÚbpeÁ  sF    


2





zXLMTokenizer.bper
   Fc              	   C   sä  |r| j r|| j krt d¡ |r.| ¡ }nf|| jkrh| j||d}|dkrVt|ƒ}| j||d}n,|dkrà| j||d}z(dtj	kr˜ddl
m} ntj	d j}W n. ttfk
rÔ   t d¡ t d	¡ ‚ Y nX ||ƒ}n´|d
krhz$dtj	krddl}n
tj	d }W n0 ttfk
r>   t d¡ t d¡ ‚ Y nX d | |¡¡}| j||d}| ¡ }n,|dkrŒ| j||d}|  |¡}ntdƒ‚| jrª|sªt|ƒ}g }|D ],}|r²| dd„ |  |¡ d¡D ƒ¡ q²|S )aõ  
        Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizerself. Otherwise, we use Moses.

        Details of tokenization:
        - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
            - Install with `pip install sacremoses`
        - [pythainlp](https://github.com/PyThaiNLP/pythainlp): Thai tokenizer
            - Install with `pip install pythainlp`
        - [kytea](https://github.com/chezou/Mykytea-python): Japanese tokenizer, wrapper of [KyTea](https://github.com/neubig/kytea)
            - Install with the following steps:
            ```
            git clone git@github.com:neubig/kytea.git && cd kytea
            autoreconf -i
            ./configure --prefix=$HOME/local
            make && make install
            pip install kytea
            ```
        - [jieba](https://github.com/fxsjy/jieba): Chinese tokenizer (*)
            - Install with `pip install jieba`

        (*) The original XLM used [Stanford Segmenter](https://nlp.stanford.edu/software/stanford-segmenter-2018-10-16.zip).
        However, the wrapper (`nltk.tokenize.stanford_segmenter`) is slow due to JVM overhead, and it will be deprecated.
        Jieba is a lot faster and pip-installable. Note there is some mismatch with the Stanford Segmenter. It should be fine
        if you fine-tune the model with Chinese supervisionself. If you want the same exact behaviour, use the original XLM
        [preprocessing script](https://github.com/facebookresearch/XLM/tree/master/tools) to tokenize the sentence externally,
        and set `bypass_tokenizer=True` to bypass the tokenizer.

        Args:
            - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported languages. However, we don't enforce it.
            - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)  (bool). If True, we only apply BPE.

        Returns:
            List of tokens.
        zSupplied language code not found in lang2id mapping. Please check that your language is supported by the loaded pretrained model.rJ  r   r   Z	pythainlpr   )Úword_tokenizezaMake sure you install PyThaiNLP (https://github.com/PyThaiNLP/pythainlp) with the following stepsz1. pip install pythainlpr   ÚjiebaNzUMake sure you install Jieba (https://github.com/fxsjy/jieba) with the following stepsz1. pip install jiebarë   r8   zIt should not reach herec                 S   s   g | ]}|‘qS rè   rè   )r)  r  rè   rè   ré   r1  C  s     z*XLMTokenizer._tokenize.<locals>.<listcomp>)r   rY  rZ  ró   r7  rR  r  rP  ÚsysÚmodulesZpythainlp.tokenizerr  rW  rX  rs  rí   Zcutr\  rk  r   rø   rl  rq  )rF  rõ   rK  Zbypass_tokenizerZth_word_tokenizers  Zsplit_tokensrm  rè   rè   ré   Ú	_tokenizeí  s^    #ÿ

ÿ







$zXLMTokenizer._tokenizec                 C   s   | j  || j  | j¡¡S )z2 Converts a token (str) in an id using the vocab. )r>  rb  r  )rF  rm  rè   rè   ré   Ú_convert_token_to_idG  s    z!XLMTokenizer._convert_token_to_idc                 C   s   | j  || j¡S )z=Converts an index (integer) in a token (str) using the vocab.)r@  rb  r  )rF  rj  rè   rè   ré   Ú_convert_id_to_tokenK  s    z!XLMTokenizer._convert_id_to_tokenc                 C   s   d  |¡ dd¡ ¡ }|S )z< Converts a sequence of tokens (string) in a single string. rì   r`  rë   )rí   r	  Ústrip)rF  ÚtokensZ
out_stringrè   rè   ré   Úconvert_tokens_to_stringO  s    z%XLMTokenizer.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.
        A XLM sequence has the following format:

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

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

        Returns:
            :obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.

        N)Zbos_token_idÚsep_token_id)rF  r|  r}  ZbosÚseprè   rè   ré   Ú build_inputs_with_special_tokensT  s
    z-XLMTokenizer.build_inputs_with_special_tokens)r|  r}  Úalready_has_special_tokensr~  c                    sz   |r*|dk	rt dƒ‚tt‡ fdd„|ƒƒS |dk	r`dgdgt|ƒ  dg dgt|ƒ  dg S dgdgt|ƒ  dg S )a  
        Retrieves 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`` or ``encode_plus`` methods.

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of ids.
            token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
                Set to True if the token list is already formatted with special tokens for the model

        Returns:
            :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        Nz~You should not supply a second sequence if the provided sequence of ids is already formated with special tokens for the model.c                    s   | ˆ j ˆ jfkrdS dS )Nr   r   )r  Úcls_token_id)Úxr]  rè   ré   re  ‰  rf  z6XLMTokenizer.get_special_tokens_mask.<locals>.<lambda>r   r   )rk  r[  Úmapr8  )rF  r|  r}  r‚  rè   r]  ré   Úget_special_tokens_maskp  s    ÿ.z$XLMTokenizer.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ù  
        Creates 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, only returns the first portion of the mask (0s).

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of ids.
            token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
                Optional second list of IDs for sequence pairs.

        Returns:
            :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
            sequence(s).
        Nr   r   )r  rƒ  r8  )rF  r|  r}  r€  Úclsrè   rè   ré   Ú$create_token_type_ids_from_sequences  s
    z1XLMTokenizer.create_token_type_ids_from_sequencesc           	   	   C   sò   t j |¡s t d |¡¡ dS t j |td ¡}t j |td ¡}t|ddd}| 	t
j| jdd	¡ W 5 Q R X d
}t|ddd^}t| j ¡ dd„ dD ]@\}}||krÂt d |¡¡ |}| 	d |¡d ¡ |d7 }qžW 5 Q R X ||fS )a  
        Save the vocabulary and special tokens file to a directory.

        Args:
            save_directory (:obj:`str`):
                The directory in which to save the vocabulary.

        Returns:
            :obj:`Tuple(str)`: Paths to the files saved.
        z*Vocabulary path ({}) should be a directoryNr   r   Úwr&  r'  F)Úensure_asciir   c                 S   s   | d S )Nr   rè   )Úkvrè   rè   ré   re  Ã  rf  z.XLMTokenizer.save_vocabulary.<locals>.<lambda>rg  zqSaving vocabulary to {}: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!rë   r-  r   )rT  rU  ÚisdirrY  rZ  Úformatrí   ÚVOCAB_FILES_NAMESr;  Úwriter<  Údumpsr>  ÚsortedrD  r?  Úwarning)	rF  Zsave_directoryr   Z
merge_fileÚfrj  ÚwriterZ
bpe_tokensZtoken_indexrè   rè   ré   Úsave_vocabulary­  s(     ÿÿzXLMTokenizer.save_vocabulary)r
   F)N)NF)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_sizesr3  rM  rP  rR  r\  Úpropertyr^  r_  rq  rv  rw  rx  r{  r   Úintr   r  Úboolr†  rˆ  r•  Ú__classcell__rè   rè   rH  ré   r    sv   :öè>
,
Z ÿ 
þ   ÿ 
 þ  ÿ 
þr  )r™  r<  ÚloggingrT  r
  rt  rï   Útypingr   r   Z
sacremosesrL  Ztokenization_utilsr   Ú	getLoggerr–  rY  rŽ  rš  rœ  r›  rê   rø   r  r  r  r  rè   rè   rè   ré   Ú<module>   s  
þööóöýýýññí&ññí&ýýïïë*œgœ˜€ ò  b+