o
    ߥi:                     @   s   d 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
 ddlmZmZ ddlmZ ddlmZ e Zd	d
dZddiddidZddiZdejiZdddiiZddiZdddiiZG dd de
Zdd Zdd ZG dd deZdS )zTokenization classes for OFA.    N)ListOptionalTuple)PreTrainedTokenizer)BartTokenizer)BasicTokenizerWordpieceTokenizer)logging)	ModelFilez
vocab.jsonz
merges.txt)
vocab_filemerges_filezofa-basez7https://huggingface.co/ofa-base/resolve/main/vocab.jsonz7https://huggingface.co/ofa-base/resolve/main/merges.txti   r   zbert-base-chinesez?https://huggingface.co/bert-base-chinese/resolve/main/vocab.txtdo_lower_caseTc                   @   s   e Zd ZdZeZeZeZ	dS )OFATokenizera  
    Construct a OFA tokenizer.

    [`~OFATokenizer`] is identical to [`BartTokenizer`] and runs end-to-end tokenization: punctuation splitting and
    wordpiece.

    Refer to superclass [`BartTokenizer`] for usage examples and documentation concerning parameters.
    N)
__name__
__module____qualname____doc__VOCAB_FILES_NAMESvocab_files_namesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESmax_model_input_sizes r   r   f/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/multi_modal/ofa/tokenization_ofa.pyr   F   s
    	r   c                 C   sf   t  }t| ddd}| }W d   n1 sw   Y  t|D ]\}}|d}|||< q#|S )z*Loads a vocabulary file into a dictionary.rutf-8encodingN
)collectionsOrderedDictopen	readlines	enumeraterstrip)r   vocabreadertokensindextokenr   r   r   
load_vocabU   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_tokenize`   s
   r/   c                
       s4  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dd Zdd Zdd Zdd Zdd Z	d)dee deee  dee fddZ		d*dee deee  dedee f fd d!Z	d)dee deee  dee fd"d#Z	d)d$ed%ee dee fd&d'Z  ZS )+OFATokenizerZHa  
    Construct a OFA 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`
        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>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_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.
        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.
        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.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        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.
        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<s></s><unk><pad><mask>c                    s   t j|std| dt|| _t jd||||||	|||
|||d| t	dd | j
 D | _|| _|rEt||||d| _t| j| j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)`)r   do_basic_tokenizenever_split	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokentokenize_chinese_charsstrip_accentsc                 S   s   g | ]\}}||fqS r   r   ).0tokidsr   r   r   
<listcomp>   s    z+OFATokenizerZH.__init__.<locals>.<listcomp>)r   r7   r?   r@   )r&   r:   r   )ospathisfile
ValueErrorr+   r&   super__init__r    r!   itemsids_to_tokensr6   r   basic_tokenizerr   r:   wordpiece_tokenizer)selfr   r   r6   r7   r8   r9   r;   r<   r:   r=   r>   r?   r@   kwargs	__class__r   r   rJ      sF   



zOFATokenizerZH.__init__c                 C   s   | j jS N)rM   r   rO   r   r   r   r      s   zOFATokenizerZH.do_lower_casec                 C   s
   t | jS rS   )lenr&   rT   r   r   r   
vocab_size   s   
zOFATokenizerZH.vocab_sizec                 C   s   t | jfi | jS rS   )dictr&   added_tokens_encoderrT   r   r   r   	get_vocab   s   zOFATokenizerZH.get_vocabc                 C   s^   g }| j r'| jj|| jdD ]}|| jjv r|| q|| j|7 }q|S | j|}|S )N)r7   )r6   rM   tokenizeall_special_tokensr7   appendrN   )rO   r.   split_tokensr*   r   r   r   	_tokenize   s   
zOFATokenizerZH._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r&   getr:   )rO   r*   r   r   r   _convert_token_to_id   s   z#OFATokenizerZH._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)rL   r_   r:   )rO   r)   r   r   r   _convert_id_to_token   s   z#OFATokenizerZH._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string. z ## )joinreplacer,   )rO   r(   
out_stringr   r   r   convert_tokens_to_string   s   z'OFATokenizerZH.convert_tokens_to_stringtoken_ids_0token_ids_1returnc                 C   s@   |du r| j g| | jg S | j g}| jg}|| | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A BERT sequence has the following format:

        - single sequence: `[CLS] X [SEP]`
        - pair of sequences: `[CLS] A [SEP] B [SEP]`

        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)cls_token_idsep_token_id)rO   rh   ri   clssepr   r   r    build_inputs_with_special_tokens  s
   z/OFATokenizerZH.build_inputs_with_special_tokensF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)rh   ri   rp   N   r   )rI   get_special_tokens_maskrU   )rO   rh   ri   rp   rQ   r   r   rr     s   z&OFATokenizerZH.get_special_tokens_maskc                 C   sV   | j g}| jg}|du 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. A BERT 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   rq   )rl   rk   rU   )rO   rh   ri   rn   rm   r   r   r   $create_token_type_ids_from_sequences?  s   z3OFATokenizerZH.create_token_type_ids_from_sequencessave_directoryfilename_prefixc                 C   s   d}t j|rt j||r|d ndtd  }n
|r |d nd| }t|ddd4}t| j dd	 d
D ]\}}||krJt	
d| d |}||d  |d7 }q7W d    |fS 1 sbw   Y  |fS )Nr   -rc   r   wr   r   c                 S   s   | d S )Nrq   r   )kvr   r   r   <lambda>l  s    z0OFATokenizerZH.save_vocabulary.<locals>.<lambda>)keyzSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   rq   )rE   rF   isdirrd   r   r"   sortedr&   rK   loggerwarningwrite)rO   rt   ru   r)   r   writerr*   token_indexr   r   r   save_vocabulary^  s<   




zOFATokenizerZH.save_vocabulary)TTNr1   r2   r2   r1   r3   r4   r5   TNrS   )NF) r   r   r   r   VOCAB_FILES_NAMES_ZHr   PRETRAINED_VOCAB_FILES_MAP_ZHr    PRETRAINED_INIT_CONFIGURATION_ZHpretrained_init_configuration)PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES_ZHr   rJ   propertyr   rV   rY   r^   r`   ra   rg   r   intr   ro   boolrr   rs   strr   r   __classcell__r   r   rQ   r   r0   i   s~    <3




#

!r0   ) r   r    rE   typingr   r   r   transformersr   *transformers.models.bart.tokenization_bartr   *transformers.models.bert.tokenization_bertr   r   transformers.utilsr	   modelscope.utils.constantr
   
get_loggerr}   r   r   r   
VOCAB_FILEr   r   r   r   r   r+   r/   r0   r   r   r   r   <module>   sD   

	