a
    d                     @   s@  d 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
mZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZ d	d
lmZ d	dlmZ d	dl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d	dl+m,Z,m-Z-m.Z. e./e0Z1dZ2dZ3dZ4dZ5e!d7 Z!eeeedZ6de2iZ7e-e!G dd de&Z8dS )z
 Tokenization classes for fast tokenizers (provided by HuggingFace's tokenizers library). For slow (python) tokenizers
 see tokenization_utils.py
    N)defaultdict)AnyDictListOptionalTupleUnion)Encoding)	Tokenizer)Decoder)
BpeTrainerUnigramTrainerWordLevelTrainerWordPieceTrainer   )convert_slow_tokenizer)PreTrainedTokenizer)
INIT_TOKENIZER_DOCSTRING
AddedTokenBatchEncodingPreTokenizedInputPreTokenizedInputPairPreTrainedTokenizerBaseSpecialTokensMixin	TextInputTextInputPairTruncationStrategy)PaddingStrategyadd_end_docstringsloggingztokenizer.jsonzspecial_tokens_map.jsonztokenizer_config.jsonzadded_tokens.jsonu  
        tokenizer_object ([`tokenizers.Tokenizer`]):
            A [`tokenizers.Tokenizer`] object from 🤗 tokenizers to instantiate from. See [Using tokenizers from 🤗
            tokenizers](../fast_tokenizers) for more information.
        tokenizer_file ([`str`]):
            A path to a local JSON file representing a previously serialized [`tokenizers.Tokenizer`] object from 🤗
            tokenizers.
)BPEUnigram	WordLevel	WordPiecetokenizer_filec                       sh  e Zd ZU dZeZdZeed< dZ	e
ed<  fddZee
dd	d
ZeedddZeeef dddZeeeef dddZeeef dddZedddZeedddZeedddZdFeee
 ee
 e
e
e
e
e
eeeef ee f d	ddZe eee f e eee f dddZ!eed d!d"Z"eee d#d$d%Z#dGee ee$f  ed&d'd(Z%dHe
ed)d*d+Z&dIe eee f e
e eee f d,d-d.Z'dJeee e
ee d/d0d1Z(e)e*eeee d2d3d4Z+de)j,e*j-dd5ddddddddddfe ee. ee/ ee0 ee1 f e
e)e*ee ee
ee ee ee
 ee
 e
e
e
e
e
e2d6d7d8Z3dde)j,e*j-dd5ddddddddddfe e.e0f ee e.e0f  e
e)e*ee ee
ee ee
 ee
 ee
 e
e
e
e
e
e2d9d:d;Z4ee edd<d=Z5dKe eee f e
e
ed>d?d@Z6dLe ee7j8f ee ee
 ee ee dAdBdCZ9dMdDdEZ:  Z;S )NPreTrainedTokenizerFastaQ  
    Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).

    Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].

    Handles all the shared methods for tokenization and special tokens, as well as methods for
    downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.

    This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the
    specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
    Nslow_tokenizer_classTcan_save_slow_tokenizerc                    s   | dd }| dd }| dd }| dd}|rN|d u rN| jd u rNtd|d urbt|}nV|d urz|szt|}n>|d urt|}n,| jd ur| j|i |}t|}ntd|| _|d ur|	|j
 d| _t jf i | d S )Ntokenizer_objectZ__slow_tokenizerr$   	from_slowFzCannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you have sentencepiece installed.a-  Couldn't instantiate the backend tokenizer from one of: 
(1) a `tokenizers` library serialization file, 
(2) a slow tokenizer instance to convert or 
(3) an equivalent slow tokenizer class to instantiate and convert. 
You need to have sentencepiece installed to convert a slow tokenizer to a fast one.)popr&   
ValueErrorcopydeepcopyTokenizerFast	from_filer   
_tokenizerupdateinit_kwargs_decode_use_source_tokenizersuper__init__)selfargskwargsr(   Zslow_tokenizerZfast_tokenizer_filer)   Zfast_tokenizer	__class__ m/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/tokenization_utils_fast.pyr5   _   s2    


z PreTrainedTokenizerFast.__init__)returnc                 C   s   dS )NTr;   r6   r;   r;   r<   is_fast   s    zPreTrainedTokenizerFast.is_fastc                 C   s   | j jddS )zP
        `int`: Size of the base vocabulary (without the added tokens).
        FZwith_added_tokensr0   Zget_vocab_sizer>   r;   r;   r<   
vocab_size   s    z"PreTrainedTokenizerFast.vocab_sizec                 C   s   | j jddS )NTr@   )r0   	get_vocabr>   r;   r;   r<   rC      s    z!PreTrainedTokenizerFast.get_vocabc                 C   s   |   S N)rC   r>   r;   r;   r<   vocab   s    zPreTrainedTokenizerFast.vocabc                    s6   | j jdd | j jdd} fdd| D }|S )z
        Returns the added tokens in the vocabulary as a dictionary of token to index.

        Returns:
            `Dict[str, int]`: The added tokens.
        Fr@   Tc                    s   i | ]\}}| vr||qS r;   r;   ).0tokindexZ
base_vocabr;   r<   
<dictcomp>       z;PreTrainedTokenizerFast.get_added_vocab.<locals>.<dictcomp>)r0   rC   items)r6   Z
full_vocabadded_vocabr;   rI   r<   get_added_vocab   s    z'PreTrainedTokenizerFast.get_added_vocabc                 C   s   | j jddS )zD
        Size of the full vocabulary with the added tokens.
        Tr@   rA   r>   r;   r;   r<   __len__   s    zPreTrainedTokenizerFast.__len__c                 C   s   | j S )zc
        `tokenizers.implementations.BaseTokenizer`: The Rust tokenizer used as a backend.
        )r0   r>   r;   r;   r<   backend_tokenizer   s    z)PreTrainedTokenizerFast.backend_tokenizerc                 C   s   | j jS )zU
        `tokenizers.decoders.Decoder`: The Rust decoder for this tokenizer.
        )r0   decoderr>   r;   r;   r<   rQ      s    zPreTrainedTokenizerFast.decoderF)	encodingreturn_token_type_idsreturn_attention_maskreturn_overflowing_tokensreturn_special_tokens_maskreturn_offsets_mappingreturn_lengthverboser=   c	                 C   s   |du rd| j v }|du r$d| j v }|r@|jdur@|g|j }	n|g}	tt}
|	D ]|}|
d |j |rz|
d |j |r|
d |j |r|
d |j |r|
d |j	 |rR|
d t
|j qR|
|	fS )a  
        Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list
        of encodings, take care of building a batch from overflowing tokens.

        Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are
        lists (overflows) of lists (tokens).

        Output shape: (overflows, sequence length)
        NZtoken_type_idsattention_mask	input_idsspecial_tokens_maskZoffset_mappinglength)Zmodel_input_namesZoverflowingr   listappendidsZtype_idsrZ   r\   offsetslen)r6   rR   rS   rT   rU   rV   rW   rX   rY   	encodingsZencoding_dicter;   r;   r<   _convert_encoding   s*    

z)PreTrainedTokenizerFast._convert_encoding)tokensr=   c                    s2   |du rdS t |tr  |S  fdd|D S )aT  
        Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the
        vocabulary.

        Args:
            tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s).

        Returns:
            `int` or `List[int]`: The token id or list of token ids.
        Nc                    s   g | ]}  |qS r;   )#_convert_token_to_id_with_added_vocrF   tokenr>   r;   r<   
<listcomp>   rK   zAPreTrainedTokenizerFast.convert_tokens_to_ids.<locals>.<listcomp>)
isinstancestrrg   r6   rf   r;   r>   r<   convert_tokens_to_ids   s
    

z-PreTrainedTokenizerFast.convert_tokens_to_ids)ri   r=   c                 C   s   | j |}|d u r| jS |S rD   )r0   token_to_idZunk_token_id)r6   ri   rH   r;   r;   r<   rg      s    z;PreTrainedTokenizerFast._convert_token_to_id_with_added_voc)rH   r=   c                 C   s   | j t|S rD   )r0   id_to_tokenint)r6   rH   r;   r;   r<   _convert_id_to_token  s    z,PreTrainedTokenizerFast._convert_id_to_token)
new_tokensr=   c                 C   s   |r| j |S | j |S rD   )r0   add_special_tokensZ
add_tokens)r6   rs   special_tokensr;   r;   r<   _add_tokens  s    z#PreTrainedTokenizerFast._add_tokens)pairr=   c                 C   s   | j |S )aG  
        Returns the number of added tokens when encoding a sequence with special tokens.

        <Tip>

        This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
        this inside your training loop.

        </Tip>

        Args:
            pair (`bool`, *optional*, defaults to `False`):
                Whether the number of added tokens should be computed in the case of a sequence pair or a single
                sequence.

        Returns:
            `int`: Number of special tokens added to sequences.
        )r0   num_special_tokens_to_add)r6   rw   r;   r;   r<   rx     s    z1PreTrainedTokenizerFast.num_special_tokens_to_add)r`   skip_special_tokensr=   c                 C   sR   t |tr| j|S g }|D ].}t|}|r:|| jv r:q|| j| q|S )a  
        Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
        added tokens.

        Args:
            ids (`int` or `List[int]`):
                The token id (or token ids) to convert to tokens.
            skip_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to remove special tokens in the decoding.

        Returns:
            `str` or `List[str]`: The decoded token(s).
        )rk   rq   r0   rp   Zall_special_idsr_   )r6   r`   ry   rf   rH   r;   r;   r<   convert_ids_to_tokens"  s    
z-PreTrainedTokenizerFast.convert_ids_to_tokens)textrw   rt   r=   c                 K   s   | j f |||d| S )N)r{   	text_pairrt   )Zencode_plusrf   )r6   r{   rw   rt   r8   r;   r;   r<   tokenize<  s    z PreTrainedTokenizerFast.tokenizepadding_strategytruncation_strategy
max_lengthstridepad_to_multiple_ofc           
         s   | j j | j j}|tjkr. durz| j   nL|||j| jd} du rNd}n fdd|D }||krz| j jf i | |t	j
kr|dur| j   nF|t	jkr|nd}	|	| j| j| j| j|d}||kr| j jf i | dS )a  
        Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers
        library) and restore the tokenizer settings afterwards.

        The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a
        padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed
        section.

        Args:
            padding_strategy ([`~utils.PaddingStrategy`]):
                The kind of padding that will be applied to the input
            truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
                The kind of truncation that will be applied to the input
            max_length (`int`):
                The maximum size of a sequence.
            stride (`int`):
                The stride to use when handling overflow.
            pad_to_multiple_of (`int`, *optional*):
                If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
                the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
        N)r   r   Zstrategy	directionc                    s   i | ]}|  |d qS rD   get)rF   kZ_truncationr;   r<   rJ   q  rK   zFPreTrainedTokenizerFast.set_truncation_and_padding.<locals>.<dictcomp>)r]   r   Zpad_id	pad_tokenZpad_type_idr   )r0   Z
truncationpaddingr   DO_NOT_TRUNCATEZno_truncationvalueZtruncation_sideZenable_truncationr   
DO_NOT_PADZ
no_paddingZ
MAX_LENGTHZpadding_sideZpad_token_idr   Zpad_token_type_idZenable_padding)
r6   r   r   r   r   r   Z_paddingtargetcurrentr]   r;   r   r<   set_truncation_and_padding?  s8    

z2PreTrainedTokenizerFast.set_truncation_and_paddingr   )batch_text_or_text_pairsrt   r   r   r   r   is_split_into_wordsr   return_tensorsrS   rT   rU   rV   rW   rX   rY   r=   c                    s  t |ttfs"tdt| dj|||||d jj|||d}fdd|D }i }|d d  D ]  fdd|D }|| < q|d	d |D }rg }t	|D ]"\}\}}||gt
|d
  7 }q||d< |d
 D ]}|| qt|||	dS )Nz:batch_text_or_text_pairs has to be a list or a tuple (got )r~   )rt   Zis_pretokenizedc                    s&   g | ]}j | d qS ))rR   rS   rT   rU   rV   rW   rX   rY   )re   )rF   rR   )rT   rX   rW   rU   rV   rS   r6   rY   r;   r<   rj     s   z>PreTrainedTokenizerFast._batch_encode_plus.<locals>.<listcomp>r   c                    s"   g | ]\}}|  D ]}|qqS r;   r;   )rF   item_rd   )keyr;   r<   rj     rK   c                 S   s   g | ]\}}|D ]}|qqS r;   r;   )rF   r   r   rd   r;   r;   r<   rj     rK   r[   overflow_to_sample_mapping)Ztensor_type)rk   tupler^   	TypeErrortyper   r0   Zencode_batchkeys	enumeraterb   &_eventual_warn_about_too_long_sequencer   )r6   r   rt   r   r   r   r   r   r   r   rS   rT   rU   rV   rW   rX   rY   rc   Ztokens_and_encodingsZsanitized_tokensstackZsanitized_encodingsr   itoksr   r[   r;   )	r   rT   rX   rW   rU   rV   rS   r6   rY   r<   _batch_encode_plus  s@    
z*PreTrainedTokenizerFast._batch_encode_plus)r{   r|   rt   r   r   r   r   r   r   r   rS   rT   rU   rV   rW   rX   rY   r=   c                 K   s   |r||fgn|g}| j |f|||||||	|
|||||||d|}|
d u rl|sltdd | D |j}| |d || |S )N)r   rt   r   r   r   r   r   r   rS   rT   rU   rV   rW   rX   rY   c                 S   s8   i | ]0\}}|t |d kr0t|d  tr0|d  n|qS )r   )rb   rk   r^   )rF   r   r   r;   r;   r<   rJ   	  s   z8PreTrainedTokenizerFast._encode_plus.<locals>.<dictcomp>r[   )r   r   rL   rc   r   )r6   r{   r|   rt   r   r   r   r   r   r   r   rS   rT   rU   rV   rW   rX   rY   r8   Zbatched_inputZbatched_outputr;   r;   r<   _encode_plus  s>    z$PreTrainedTokenizerFast._encode_plusc                 C   s   | j j|S rD   )rP   rQ   decoderm   r;   r;   r<   convert_tokens_to_string  s    z0PreTrainedTokenizerFast.convert_tokens_to_string)	token_idsry   clean_up_tokenization_spacesr=   c                 K   sZ   | dd| _t|tr|g}| jj||d}|d ur:|n| j}|rR| |}|S |S d S )NZuse_source_tokenizerF)ry   )r*   r3   rk   rq   r0   r   r   Zclean_up_tokenization)r6   r   ry   r   r8   r{   Z
clean_textr;   r;   r<   _decode  s    

zPreTrainedTokenizerFast._decode)save_directory
file_nameslegacy_formatfilename_prefixr=   c                 C   s*  t |}| jdu r"|du r"td|du s2|du o@| jduo@| j}|du pP|du }|rtj||rj|d ndt }|  }|rt	|ddd	0}	t
j|d
dddd }
|	|
 W d   n1 s0    Y  | j||d}|| |f }|r&tj||r|d ndt }| j| ||f }|S )z
        Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON
        file containing {config + vocab + added-tokens}.
        NTzYour tokenizer does not have a legacy version defined and therefore cannot register this version. You might consider leaving the legacy_format at `None` or setting it to `False`.F- wzutf-8)rR      )indent	sort_keysensure_ascii
)r   )rl   r&   r+   r'   ospathjoinADDED_TOKENS_FILErN   openjsondumpswriteZsave_vocabularyTOKENIZER_FILErP   save)r6   r   r   r   r   Z	save_slowZ	save_fastZadded_tokens_filerM   fZout_strZvocab_filesr$   r;   r;   r<   _save_pretrained/  s:    (
z(PreTrainedTokenizerFast._save_pretrainedc                    s  t | j }|d}|d}	d}
|d d dkrRi |d d< g |d d< n|d d d	kr|d d
 dur|d d
 }|d d | d }
 dur|
 v r |
 }
d|d d
< |
dgg|d d< n6|d d dv ri |d d< ntd|d d  d durBd|d v rB|d d  v rB |d d  |d d< tt |g }|D ]v}|dd}|dd}|d d d	kr|sqZ dur|d  v r |d  |d< |	t
f i | qZ|dur|| |d d dkr$d|vr$|d d dur$|d d |d< |d d dkrbd|vrb|d d durb|d d |d< |d d d	kr|
dur|
|d< |d dur|d d dkrtj |d< t|d d  }|f ||d|}j|||d |	durt  }d|	v rt|	d D ]`}|	d | d } durB fdd|D }||	d | d< fdd|D |	d | d < qd!D ]N}||	v rx|	| \}} dur| v r | }|}||g|	|< qx|	|d< tt || j }tj }|d" |D ]}t| d#| durt| |} durB| v rB | }t| d#| }t|t
r~t
||j|j|j|jd$||< n|||< q| j}|dur|| t|dkr||d"< | jf d%i|S )&uG  
        Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)
        as the current one.

        Args:
            text_iterator (generator of `List[str]`):
                The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
                if you have everything in memory.
            vocab_size (`int`):
                The size of the vocabulary you want for your tokenizer.
            length (`int`, *optional*):
                The total number of sequences in the iterator. This is used to provide meaningful progress tracking
            new_special_tokens (list of `str` or `AddedToken`, *optional*):
                A list of new special tokens to add to the tokenizer you are training.
            special_tokens_map (`Dict[str, str]`, *optional*):
                If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special
                token name to new special token name in this argument.
            kwargs:
                Additional keyword arguments passed along to the trainer from the 🤗 Tokenizers library.

        Returns:
            [`PreTrainedTokenizerFast`]: A new tokenizer of the same type as the original one, trained on
            `text_iterator`.

        added_tokenspost_processorNmodelr   r    rE   Zmergesr!   unk_idr   g        )r"   r#   z;This method does not support this type of tokenizer (found z-) only BPE, Unigram, WordLevel and WordPiece.	unk_tokenspecialidcontentZcontinuing_subword_prefixZend_of_word_suffixZpre_tokenizer	ByteLevelZinitial_alphabet)rB   ru   )r]   trainerru   rf   c                    s   g | ]}  ||qS r;   r   rh   )special_tokens_mapr;   r<   rj     rK   zCPreTrainedTokenizerFast.train_new_from_iterator.<locals>.<listcomp>c                    s   g | ]}  |qS r;   )ro   rh   )	tokenizerr;   r<   rj     rK   r`   )clssepadditional_special_tokensr   )single_wordlstriprstrip
normalizedr(   ) r   loadsr0   Zto_strr*   r+   r.   Zfrom_strr   r_   r   extendpre_tokenizers_fastr   alphabetMODEL_TO_TRAINER_MAPPINGZtrain_from_iteratorro   r2   r,   r   ZSPECIAL_TOKENS_ATTRIBUTESremovegetattrrk   r   r   r   r   r   rb   r:   )r6   Ztext_iteratorrB   r]   Znew_special_tokensr   r8   Ztokenizer_jsonr   r   r   r   ru   Zadded_tokenr   r   Ztrainer_classr   Ztrained_tokenizer_jsonr   rf   Zspecial_tokenri   Ztoken_idZspecial_tokens_listZspecial_token_fullr   r;   )r   r   r<   train_new_from_iterator_  s    "




 


"







z/PreTrainedTokenizerFast.train_new_from_iterator)NNFFFFT)F)F)F)NF)FN)NN)NNN)<__name__
__module____qualname____doc__VOCAB_FILES_NAMESZvocab_files_namesr&   r   __annotations__r'   boolr5   propertyr?   rq   rB   r   rl   rC   rE   rN   rO   r.   rP   DecoderFastrQ   EncodingFastr   r   r   r   re   r   rn   rg   rr   r   rv   rx   rz   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   PathLiker   r   __classcell__r;   r;   r9   r<   r%   M   s&  
+	       /( LX
9    4   r%   )9r   r,   r   r   collectionsr   typingr   r   r   r   r   r   Ztokenizers.pre_tokenizersZpre_tokenizersr   Z
tokenizersr	   r   r
   r.   Ztokenizers.decodersr   r   Ztokenizers.trainersr   r   r   r   r   Ztokenization_utilsr   Ztokenization_utils_baser   r   r   r   r   r   r   r   r   r   utilsr   r   r   Z
get_loggerr   loggerr   ZSPECIAL_TOKENS_MAP_FILEZTOKENIZER_CONFIG_FILEr   r   r   r%   r;   r;   r;   r<   <module>   s8    0

