o
    i ]                     @   s   d dl Z d dl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
 ddlmZ eeZdddZd	d
 Zdd Zdd Zdd ZG dd dZG dd deZdgZdS )    N)Optional   )PreTrainedTokenizer_is_control_is_punctuation_is_whitespace)loggingz
vocab.jsonz
merges.txt)
vocab_filemerges_filec                 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pairs	prev_charchar r   m/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/transformers/models/herbert/tokenization_herbert.py	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   ’'u   …z...u   ━-u   〈<u   〉>u   【[u   】]u   ％%)replaceresub)textr   r   r   replace_unicode_punct0   sJ   r3   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)r2   outputr   catr   r   r   remove_non_printing_char\   s   


r=   c                 C   s   |   } | sg S |  }|S )z@Runs basic whitespace cleaning and splitting on a piece of text.)stripsplit)r2   tokensr   r   r   whitespace_tokenizej   s
   rA   c                   @   sX   e Zd ZdZ					dddZdddZdd	 Zdd
dZdd Zdd Z	dd Z
dS )BasicTokenizera  
    Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

    Args:
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters.

            This should likely be deactivated for Japanese (see this
            [issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original BERT).
        do_split_on_punc (`bool`, *optional*, defaults to `True`):
            In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
            the full context of the words, such as contractions.
    TNc                 C   s2   |d u rg }|| _ t|| _|| _|| _|| _d S N)do_lower_caser   never_splittokenize_chinese_charsstrip_accentsdo_split_on_punc)selfrD   rE   rF   rG   rH   r   r   r   __init__   s   

zBasicTokenizer.__init__c                 C   s   |r
| j t|n| j }| |}| jr| |}td|}t|}g }|D ])}||vrH| j	r@|
 }| jdur?| |}n| jrH| |}|| || q(td|}|S )aj  
        Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

        Args:
            never_split (`List[str]`, *optional*)
                Kept for backward compatibility purposes. Now implemented directly at the base class level (see
                [`PreTrainedTokenizer.tokenize`]) List of token not to split.
        NFCF )rE   unionr   _clean_textrF   _tokenize_chinese_charsr6   	normalizerA   rD   lowerrG   _run_strip_accentsextend_run_split_on_puncr:   )rI   r2   rE   unicode_normalized_textorig_tokenssplit_tokenstokenoutput_tokensr   r   r   tokenize   s&   





zBasicTokenizer.tokenizec                 C   sB   t d|}g }|D ]}t |}|dkrq
|| q
d|S )z$Strips accents from a piece of text.NFDMnr5   )r6   rP   r7   r9   r:   )rI   r2   r;   r   r<   r   r   r   rR      s   

z!BasicTokenizer._run_strip_accentsc                 C   s   | j r|dur||v r|gS t|}d}d}g }|t|k rI|| }t|r/||g d}n|r6|g  d}|d | |d7 }|t|k sdd |D S )	z&Splits punctuation on a piece of text.Nr   TFr   c                 S   s   g | ]}d  |qS )r5   )r:   ).0xr   r   r   
<listcomp>       z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)rH   listlenr   r9   )rI   r2   rE   charsistart_new_wordr;   r   r   r   r   rT      s$   
z!BasicTokenizer._run_split_on_puncc                 C   sT   g }|D ] }t |}| |r|d || |d q|| qd|S )z)Adds whitespace around any CJK character.rL   r5   )ord_is_chinese_charr9   r:   rI   r2   r;   r   cpr   r   r   rO      s   



z&BasicTokenizer._tokenize_chinese_charsc                 C   s   |dkr|dks@|dkr|dks@|dkr|dks@|dkr |dks@|d	kr(|d
ks@|dkr0|dks@|dkr8|dks@|dkrB|dkrBdS dS )z6Checks whether CP is the codepoint of a CJK character.i N  i  i 4  iM  i   iߦ i  i? i@ i i  i i   i  i  i TFr   )rI   rj   r   r   r   rh      s   zBasicTokenizer._is_chinese_charc                 C   sX   g }|D ]"}t |}|dks|dkst|rqt|r!|d q|| qd|S )zBPerforms invalid character removal and whitespace cleanup on text.r   i  rL   r5   )rg   r   r   r9   r:   ri   r   r   r   rN     s   
zBasicTokenizer._clean_text)TNTNTrC   )__name__
__module____qualname____doc__rJ   rZ   rR   rT   rO   rh   rN   r   r   r   r   rB   t   s    

&
rB   c                       s4  e Zd ZdZeZddddddddg d	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 Zd d! Zd"d# Z	d4d$ee d%eee  d&ee fd'd(Z	d5d$ee d%eee  d)ed&ee f fd*d+Zd4d,ed-ee d&ee fd.d/Zd0d1 Zd2d3 Z  ZS )6HerbertTokenizera  
    Construct a BPE tokenizer for HerBERT.

    Peculiarities:

    - uses BERT's pre-tokenizer: BaseTokenizer splits tokens on spaces, and also on punctuation. Each occurrence of a
      punctuation character will be treated separately.

    - Such pretokenized input is BPE subtokenized

    This tokenizer inherits from [`XLMTokenizer`] which contains most of the methods. Users should refer to the
    superclass for more information regarding methods.
    Nz<s>z<unk>z<pad>z<mask>z</s>F)
z
<special0>z
<special1>z
<special2>z
<special3>z
<special4>z
<special5>z
<special6>z
<special7>z
<special8>z
<special9>c                    s  zdd l }W n ty   tdw || _i | _i | _h d| _|
| _|| _|| _|d ur;|d ur;t	|t	|ks;J d | _
d | _t|dd}t|| _W d    n1 sXw   Y  dd | j D | _t|dd}| dd d	 }W d    n1 sw   Y  d
d |D }tt|tt	|| _i | _t jd||	||||||||
d d| td| jddd| _d S )Nr   zrYou need to install sacremoses to use HerbertTokenizer. See https://pypi.org/project/sacremoses/ for installation.>   jathzhutf-8encodingc                 S   s   i | ]\}}||qS r   r   )r^   kvr   r   r   
<dictcomp>]  ra   z-HerbertTokenizer.__init__.<locals>.<dictcomp>
r]   c                 S   s    g | ]}t | d d qS )N   )tupler?   )r^   merger   r   r   r`   `  s     z-HerbertTokenizer.__init__.<locals>.<listcomp>)	unk_token	bos_token	sep_token	pad_token	cls_token
mask_tokenadditional_special_tokenslang2idid2langdo_lowercase_and_remove_accenttokenizer_fileF)rD   rE   rF   rG   r   )
sacremosesImportErrorsmcache_moses_punct_normalizercache_moses_tokenizerlang_with_custom_tokenizerr   r   r   rc   ja_word_tokenizerzh_word_tokenizeropenjsonloadencoderitemsdecoderreadr?   dictziprange	bpe_rankscachesuperrJ   rB   all_special_tokensbert_pre_tokenizer)rI   r	   r
   r   r   r}   r   r   r   r~   r   r   r   r   kwargsr   vocab_handlemerges_handlemerges	__class__r   r   rJ   &  sb   
zHerbertTokenizer.__init__c                 C   s   | j S rC   )r   rI   r   r   r   rD   z  s   zHerbertTokenizer.do_lower_casec                 C   s8   || j vr| jj|d}|| j |< n| j | }||S )Nlang)r   r   MosesPunctNormalizerrP   )rI   r2   r   punct_normalizerr   r   r   moses_punct_norm  s
   


z!HerbertTokenizer.moses_punct_normc                 C   s>   || j vr| jj|d}|| j |< n| j | }|j|dddS )Nr   F)
return_strescape)r   r   MosesTokenizerrZ   )rI   r2   r   moses_tokenizerr   r   r   moses_tokenize  s
   

zHerbertTokenizer.moses_tokenizec                 C   s    t |}| ||}t|}|S rC   )r3   r   r=   )rI   r2   r   r   r   r   moses_pipeline  s   zHerbertTokenizer.moses_pipelinec              	   C   s   | j d u rBzdd l}|dtjd d| _ W n( ttfyA   td td td td td	 td
  w t	| j 
|S )Nr   z-model r'   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)r   Mykyteaospath
expanduserAttributeErrorr   loggererrorrb   getWS)rI   r2   r   r   r   r   ja_tokenize  s$   






zHerbertTokenizer.ja_tokenizec                 C   s
   t | jS rC   )rc   r   r   r   r   r   
vocab_size  s   
zHerbertTokenizer.vocab_sizec                 C   s   t | jfi | jS rC   )r   r   added_tokens_encoderr   r   r   r   	get_vocab  s   zHerbertTokenizer.get_vocabc           
         s~  t |d d |d d f }| jv r j| S t|}|s#|d S 	 t| fddd}| jvr4ny|\}}g }d}|t|k rz|||}	W n ty\   |||d   Y n?w ||||	  |	}|| |kr|t|d k r||d  |kr|	||  |d	7 }n|	||  |d7 }|t|k sBt |}|}t|dkrnt|}q$d

|}|dkrd}| j|< |S )Nr]   </w>Tc                    s    j | tdS )Ninf)r   getfloat)pairr   r   r   <lambda>  s    z&HerbertTokenizer.bpe.<locals>.<lambda>keyr   r   rz   rL   z
  </w>z
</w>)r{   r   r   minr   rc   index
ValueErrorrS   r9   r:   )
rI   rX   r   r   bigramfirstsecondnew_wordre   jr   r   r   bpe  sN   


,


zHerbertTokenizer.bpec                 C   s<   | j |}g }|D ]}|r|t| |d q
|S )NrL   )r   rZ   rS   rb   r   r?   )rI   r2   
pre_tokensrW   rX   r   r   r   	_tokenize  s   zHerbertTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   r   r}   )rI   rX   r   r   r   _convert_token_to_id  s   z%HerbertTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)r   r   r}   )rI   r   r   r   r   _convert_id_to_token  s   z%HerbertTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string.r5   r   rL   )r:   r/   r>   )rI   r@   
out_stringr   r   r   convert_tokens_to_string  s   z)HerbertTokenizer.convert_tokens_to_stringtoken_ids_0token_ids_1returnc                 C   s8   | j g}| jg}|du 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)bos_token_idsep_token_id)rI   r   r   bossepr   r   r    build_inputs_with_special_tokens  s
   z1HerbertTokenizer.build_inputs_with_special_tokensalready_has_special_tokensc                    sf   |rt  j||ddS |dur&d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_maskrc   )rI   r   r   r   r   r   r   r     s   .z(HerbertTokenizer.get_special_tokens_masksave_directoryfilename_prefixc           
   	   C   sL  t j|std| d d S t j||r|d ndtd  }t j||r,|d ndtd  }t|ddd	}|t	j
| jd
dddd  W d    n1 sTw   Y  d}t|ddd	8}t| j dd dD ]!\}}	||	krtd| d |	}|d|d  |d7 }qnW d    ||fS 1 sw   Y  ||fS )NzVocabulary path (z) should be a directoryr)   r5   r	   r
   wrs   rt   rz   TF)indent	sort_keysensure_asciiry   r   c                 S   s   | d S )Nr   r   )kvr   r   r   r   H  s    z2HerbertTokenizer.save_vocabulary.<locals>.<lambda>r   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!rL   r   )r   r   isdirr   r   r:   VOCAB_FILES_NAMESr   writer   dumpsr   sortedr   r   warning)
rI   r   r   r	   
merge_filefr   writer
bpe_tokenstoken_indexr   r   r   save_vocabulary8  s6    


z HerbertTokenizer.save_vocabularyc                 C   s   | j  }d |d< |S )Nr   )__dict__copy)rI   stater   r   r   __getstate__U  s   
zHerbertTokenizer.__getstate__c                 C   s4   || _ zdd l}W n ty   tdw || _d S )Nr   znYou need to install sacremoses to use XLMTokenizer. See https://pypi.org/project/sacremoses/ for installation.)r   r   r   r   )rI   dr   r   r   r   __setstate__[  s   
zHerbertTokenizer.__setstate__rC   )NF) rk   rl   rm   rn   r   vocab_files_namesrJ   propertyrD   r   r   r   r   r   r   r   r   r   r   r   rb   intr   r   boolr   strr{   r   r   r   __classcell__r   r   r   r   ro     sd    T
		
,


 ro   )r   r   r0   r6   typingr   tokenization_utilsr   r   r   r   utilsr   
get_loggerrk   r   r   r   r3   r=   rA   rB   ro   __all__r   r   r   r   <module>   s*   
,
 "  
V