U
    9%eU                     @   s   d 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	m
Z
mZmZ ddlmZ eeZddiZdd	d
dddi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G dd de	ZG dd deZG dd deZdS )z"Tokenization classes for Splinter.    N)ListOptionalTuple   )PreTrainedTokenizer_is_control_is_punctuation_is_whitespace)logging
vocab_filez	vocab.txtz?https://huggingface.co/tau/splinter-base/resolve/main/vocab.txtzDhttps://huggingface.co/tau/splinter-base-qass/resolve/main/vocab.txtz@https://huggingface.co/tau/splinter-large/resolve/main/vocab.txtzEhttps://huggingface.co/tau/splinter-large-qass/resolve/main/vocab.txt)ztau/splinter-baseztau/splinter-base-qassztau/splinter-largeztau/splinter-large-qassi   do_lower_caseFc              	   C   sR   t  }t| ddd}| }W 5 Q R X t|D ]\}}|d}|||< q2|S )z*Loads a vocabulary file into a dictionary.rutf-8encoding
)collectionsOrderedDictopen	readlines	enumeraterstrip)r   vocabreadertokensindextoken r   q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/splinter/tokenization_splinter.py
load_vocab7   s    

r   c                 C   s   |   } | sg S |  }|S )z@Runs basic whitespace cleaning and splitting on a piece of text.)stripsplit)textr   r   r   r   whitespace_tokenizeB   s
    r#   c                       s  e Zd ZdZeZeZeZ	e
Zd( fd
d	Zedd Zedd Zedd Zdd Zdd Zdd Zdd Zdd Zd)ee eee  ee dddZd*ee eee  eee d  fd!d"Zd+ee eee  ee dd#d$Zd,eee ee d%d&d'Z  Z S )-SplinterTokenizera
  
    Construct a Splinter tokenizer. Based on WordPiece.

    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`):
            File containing the vocabulary.
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        do_basic_tokenize (`bool`, *optional*, defaults to `True`):
            Whether or not to do basic tokenization before WordPiece.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        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.
        question_token (`str`, *optional*, defaults to `"[QUESTION]"`):
            The token used for constructing question representations.
        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).
    TN[UNK][SEP][PAD][CLS][MASK]
[QUESTION]c                    s   t j|std| dt|| _tdd | j D | _	|| _
|r^t||||d| _t| jt|d| _|
| _t jf ||||||||	||d
| d S )Nz&Can't find a vocabulary file at path 'z'. To load the vocabulary from a Google pretrained model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`c                 S   s   g | ]\}}||fqS r   r   ).0tokZidsr   r   r   
<listcomp>   s     z.SplinterTokenizer.__init__.<locals>.<listcomp>)r   never_splittokenize_chinese_charsstrip_accents)r   	unk_token)
r   do_basic_tokenizer.   r1   	sep_token	pad_token	cls_token
mask_tokenr/   r0   )ospathisfile
ValueErrorr   r   r   r   itemsids_to_tokensr2   BasicTokenizerbasic_tokenizerWordpieceTokenizerstrwordpiece_tokenizerquestion_tokensuper__init__)selfr   r   r2   r.   r1   r3   r4   r5   r6   rB   r/   r0   kwargs	__class__r   r   rD   |   s<    

zSplinterTokenizer.__init__c                 C   s   |  | jS )z
        `Optional[int]`: Id of the question token in the vocabulary, used to condition the answer on a question
        representation.
        )convert_tokens_to_idsrB   rE   r   r   r   question_token_id   s    z#SplinterTokenizer.question_token_idc                 C   s   | j jS N)r>   r   rJ   r   r   r   r      s    zSplinterTokenizer.do_lower_casec                 C   s
   t | jS rL   )lenr   rJ   r   r   r   
vocab_size   s    zSplinterTokenizer.vocab_sizec                 C   s   t | jf| jS rL   )dictr   Zadded_tokens_encoderrJ   r   r   r   	get_vocab   s    zSplinterTokenizer.get_vocabc                 C   s\   g }| j rL| jj|| jdD ],}|| jjkr8|| q|| j|7 }qn| j|}|S )N)r.   )r2   r>   tokenizeZall_special_tokensr.   appendrA   )rE   r"   split_tokensr   r   r   r   	_tokenize   s    zSplinterTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   getr1   )rE   r   r   r   r   _convert_token_to_id   s    z&SplinterTokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)r<   rU   r1   )rE   r   r   r   r   _convert_id_to_token   s    z&SplinterTokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string. z ## )joinreplacer    )rE   r   Z
out_stringr   r   r   convert_tokens_to_string   s    z*SplinterTokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 C   s~   |dkr| j g| | jg S | j g}| jg}| jg| dg }| jdkrb|| | | | | S || | | | | S dS )a  
        Build model inputs from a pair of sequence for question answering tasks by concatenating and adding special
        tokens. A Splinter sequence has the following format:

        - single sequence: `[CLS] X [SEP]`
        - pair of sequences for question answering: `[CLS] question_tokens [QUESTION] . [SEP] context_tokens [SEP]`

        Args:
            token_ids_0 (`List[int]`):
                The question token IDs if pad_on_right, else context tokens IDs
            token_ids_1 (`List[int]`, *optional*):
                The context token IDs if pad_on_right, else question token IDs

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        N.right)cls_token_idsep_token_idrK   rI   padding_side)rE   r]   r^   clssepquestion_suffixr   r   r    build_inputs_with_special_tokens   s    
z2SplinterTokenizer.build_inputs_with_special_tokensF)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^   ri   N   r   )rC   get_special_tokens_maskrM   )rE   r]   r^   ri   rG   r   r   rk      s      .z)SplinterTokenizer.get_special_tokens_maskc                 C   s   | j g}| jg}| jg| dg }|dkrBt|| | dg S | jdkrxt|| | | dg t|| dg  S t|| | dg t|| | dg  S dS )a  
        Create the token type IDs corresponding to the sequences passed. [What are token type
        IDs?](../glossary#token-type-ids)

        Should be overridden in a subclass if the model has a special way of building those.

        Args:
            token_ids_0 (`List[int]`): The first tokenized sequence.
            token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.

        Returns:
            `List[int]`: The token type ids.
        r`   Nr   ra   rj   )rc   rb   rK   rI   rM   rd   )rE   r]   r^   rf   re   rg   r   r   r   $create_token_type_ids_from_sequences  s    
,z6SplinterTokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixr_   c              	   C   s   d}t j|r4t j||r$|d ndtd  }n|r@|d nd| }t|dddZ}t| j dd	 d
D ]<\}}||krt	
d| d |}||d  |d7 }qnW 5 Q R X |fS )Nr   -rY   r   wr   r   c                 S   s   | d S )Nrj   r   )kvr   r   r   <lambda>:      z3SplinterTokenizer.save_vocabulary.<locals>.<lambda>)keyzSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   rj   )r7   r8   isdirrZ   VOCAB_FILES_NAMESr   sortedr   r;   loggerwarningwrite)rE   rm   rn   r   r   writerr   Ztoken_indexr   r   r   save_vocabulary1  s"     
z!SplinterTokenizer.save_vocabulary)TTNr%   r&   r'   r(   r)   r*   TN)N)NF)N)N)!__name__
__module____qualname____doc__rv   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_sizesrD   propertyrK   r   rN   rP   rT   rV   rW   r\   r   intr   rh   boolrk   rl   r@   r   r|   __classcell__r   r   rG   r   r$   K   sb   +           /


  
!    
   
r$   c                   @   sN   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 )r=   a  
    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).
    TNc                 C   s,   |d krg }|| _ t|| _|| _|| _d S rL   )r   setr.   r/   r0   )rE   r   r.   r/   r0   r   r   r   rD   Z  s    
zBasicTokenizer.__init__c                 C   s   |r| j t|n| j }| |}| jr4| |}t|}g }|D ]R}||kr| jrt| }| j	dk	r| 
|}n| j	r| 
|}|| || qDtd|}|S )a  
        Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see
        WordPieceTokenizer.

        Args:
            **never_split**: (*optional*) list of str
                Kept for backward compatibility purposes. Now implemented directly at the base class level (see
                [`PreTrainedTokenizer.tokenize`]) List of token not to split.
        FrX   )r.   unionr   _clean_textr/   _tokenize_chinese_charsr#   r   lowerr0   _run_strip_accentsextend_run_split_on_puncrZ   )rE   r"   r.   Zorig_tokensrS   r   output_tokensr   r   r   rQ   b  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.ZNFDZMnrY   )unicodedata	normalizecategoryrR   rZ   )rE   r"   outputcharcatr   r   r   r     s    
z!BasicTokenizer._run_strip_accentsc                 C   s   |dk	r||kr|gS t |}d}d}g }|t|k r|| }t|rX||g d}n |rf|g  d}|d | |d7 }q*dd |D S )	z&Splits punctuation on a piece of text.Nr   TFrj   c                 S   s   g | ]}d  |qS )rY   )rZ   )r+   xr   r   r   r-     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)listrM   r   rR   )rE   r"   r.   charsiZstart_new_wordr   r   r   r   r   r     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.rX   rY   )ord_is_chinese_charrR   rZ   rE   r"   r   r   cpr   r   r   r     s    


z&BasicTokenizer._tokenize_chinese_charsc                 C   s   |dkr|dks|dkr |dks|dkr0|dks|dkr@|dks|d	krP|d
ks|dkr`|dks|dkrp|dks|dkr|dkrd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   )rE   r   r   r   r   r     sD    
zBasicTokenizer._is_chinese_charc                 C   sX   g }|D ]D}t |}|dks|dkst|r.qt|rB|d q|| qd|S )zBPerforms invalid character removal and whitespace cleanup on text.r   i  rX   rY   )r   r   r	   rR   rZ   r   r   r   r   r     s    zBasicTokenizer._clean_text)TNTN)N)N)r}   r~   r   r   rD   rQ   r   r   r   r   r   r   r   r   r   r=   F  s   

%
r=   c                   @   s"   e Zd ZdZdddZdd ZdS )	r?   zRuns WordPiece tokenization.d   c                 C   s   || _ || _|| _d S rL   )r   r1   max_input_chars_per_word)rE   r   r1   r   r   r   r   rD     s    zWordpieceTokenizer.__init__c                 C   s   g }t |D ]}t|}t|| jkr4|| j qd}d}g }|t|k rt|}d}	||k rd||| }
|dkrd|
 }
|
| jkr|
}	q|d8 }qX|	dkrd}q||	 |}q@|r|| j q|| q|S )a  
        Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
        tokenization using the given vocabulary.

        For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.

        Args:
          text: A single token or whitespace separated tokens. This should have
            already been passed through *BasicTokenizer*.

        Returns:
          A list of wordpiece tokens.
        Fr   NrY   z##rj   T)	r#   r   rM   r   rR   r1   rZ   r   r   )rE   r"   r   r   r   Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr   r   r   rQ     s:    


zWordpieceTokenizer.tokenizeN)r   )r}   r~   r   r   rD   rQ   r   r   r   r   r?     s   
r?   )r   r   r7   r   typingr   r   r   Ztokenization_utilsr   r   r   r	   utilsr
   Z
get_loggerr}   rx   rv   r   r   r   r   r#   r$   objectr=   r?   r   r   r   r   <module>   s@   

	 | 