
    9iS                         S r SSKrSSKrSSKJrJrJrJrJr  SSK	r
SSKJr  S0 0r0 r0 rSS0r " S S\5      r " S	 S
5      rS rS rS rS rg)zaTokenization classes for DeBERTa. mainly copied from :module:`~transformers.tokenization_deberta`    N)AnyDictListOptionalTuple)PreTrainedTokenizer
vocab_filez	spm.modelc                      ^  \ rS rSrSr\r\r\	r
\r           SS\\\\4      SS4U 4S jjjr\S 5       r\S 5       rS	 rS
\S\\   4S jrS rS rS rSS jr  SU 4S jjr SS jr SS jr SS\S\\   S\\   4S jjr Sr!U =r"$ )DebertaV2Tokenizer!   aQ  
Constructs a DeBERTa-v2 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece)
and [jieba](https://github.com/fxsjy/jieba).

Args:
    vocab_file (`str`):
        [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
        contains the vocabulary necessary to instantiate a tokenizer.
    do_lower_case (`bool`, *optional*, defaults to `False`):
        Whether or not to lowercase the input when tokenizing.
    bos_token (`string`, *optional*, defaults to `"[CLS]"`):
        The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
        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`.
    eos_token (`string`, *optional*, defaults to `"[SEP]"`):
        The end of sequence token. 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`.
    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.
    sp_model_kwargs (`dict`, *optional*):
        Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
        SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
        to set:

        - `enable_sampling`: Enable subword regularization.
        - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

          - `nbest_size = {0,1}`: No sampling is performed.
          - `nbest_size > 1`: samples from the nbest_size results.
          - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
            using forward-filtering-and-backward-sampling algorithm.

        - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
          BPE-dropout.
Nsp_model_kwargsreturnc                   > Uc  0 OUU l         [        TU ]  " SUUUUUU	U
UUUU R                   S.UD6  [        R                  R                  U5      (       d  [        SU S35      eX l        X0l        X@l	        Xl
        [        UUU R                   S9U l        S U l        U R                  (       a   SS KnXl        g g ! [         a    [        S5      ef = f)N)do_lower_case	bos_token	eos_token	unk_token	sep_token	pad_token	cls_token
mask_tokensplit_by_punctsplit_chineser   z&Can't find a vocabulary file at path 'z'. To load the vocabulary from a Google pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`)r   r   r   z|You need to install jieba to split chinese and use DebertaV2Tokenizer. See https://pypi.org/project/jieba/ for installation. )r   super__init__ospathisfile
ValueErrorr   r   r   r	   SPMTokenizer
_tokenizerjiebaImportError)selfr	   r   r   r   r   r   r   r   r   r   r   r   kwargsr#   	__class__s                  m/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/models/nlp/deberta_v2/tokenization.pyr   DebertaV2Tokenizer.__init__X   s    &5%<r/ 	
'!)' 00	
 	
 ww~~j))8 E` `  +,*$&) 002 
M
 J   M!LM MMs   2B> >Cc                 ,    [        U R                  5      $ N)lenvocabr%   s    r(   
vocab_sizeDebertaV2Tokenizer.vocab_size   s    4::    c                 .    U R                   R                  $ r+   )r"   r-   r.   s    r(   r-   DebertaV2Tokenizer.vocab   s    $$$r1   c                 x    U R                   R                  5       nUR                  U R                  5       5        U$ r+   )r-   copyupdateget_added_vocab)r%   r-   s     r(   	get_vocabDebertaV2Tokenizer.get_vocab   s,    

!T))+,r1   textc                    U R                   (       a  UR                  5       nU R                  (       a;  U R                  R	                  U5       Vs/ s H  o"PM     nnSR                  U5      nU R                  R                  U5      $ s  snf )zPTake as input a string and return a list of strings (tokens) for words/sub-words )r   lowerr   r#   cutjoinr"   tokenize)r%   r:   xseg_lists       r(   	_tokenizeDebertaV2Tokenizer._tokenize   sj    ::<D#'::>>$#78#7a#7H888H%D''-- 9s   B	c                 L    U R                   R                  R                  U5      $ )z0Converts a token (str) in an id using the vocab.)r"   spm	PieceToIdr%   tokens     r(   _convert_token_to_id'DebertaV2Tokenizer._convert_token_to_id   s    "",,U33r1   c                     XR                   :  a%  U R                  R                  R                  U5      $ U R                  $ )z=Converts an index (integer) in a token (str) using the vocab.)r/   r"   rF   	IdToPiecer   )r%   indexs     r(   _convert_id_to_token'DebertaV2Tokenizer._convert_id_to_token   s>     oo- "",, 	B37>>	Br1   c                 8    U R                   R                  U5      $ )z:Converts a sequence of tokens (string) in a single string.)r"   decode)r%   tokenss     r(   convert_tokens_to_string+DebertaV2Tokenizer.convert_tokens_to_string   s    %%f--r1   c                     Uc  U R                   /U-   U R                  /-   $ U R                   /nU R                  /nX1-   U-   U-   U-   $ )a5  
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A DeBERTa 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.
)cls_token_idsep_token_id)r%   token_ids_0token_ids_1clsseps        r(    build_inputs_with_special_tokens3DebertaV2Tokenizer.build_inputs_with_special_tokens   s`    $ %%&48I8I7JJJ  !  ! 3&4s::r1   c                    > U(       a  [         TU ]  UUSS9$ Ub+  S/S/[        U5      -  -   S/-   S/[        U5      -  -   S/-   $ S/S/[        U5      -  -   S/-   $ )aw  
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 (`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)rY   rZ   already_has_special_tokens   r   )r   get_special_tokens_maskr,   )r%   rY   rZ   r`   r'   s       r(   rb   *DebertaV2Tokenizer.get_special_tokens_mask   s    ( &72''+/ 3 1 1
 "31#K 001QC7c+&&(+,#. .sqcC,,-33r1   c                     U R                   /nU R                  /nUc  [        XA-   U-   5      S/-  $ [        XA-   U-   5      S/-  [        UU-   5      S/-  -   $ )a\  
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
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).
r   ra   )rX   rW   r,   )r%   rY   rZ   r\   r[   s        r(   $create_token_type_ids_from_sequences7DebertaV2Tokenizer.create_token_type_ids_from_sequences   s    .   !  !s(3./1#553$s*+qc1C:=9> 5?BC5E E 	Er1   c                 R    UR                  SS5      nU(       d  U(       a  SU-   nX4$ )Nadd_prefix_spaceFr<   )pop)r%   r:   is_split_into_wordsr&   rh   s        r(   prepare_for_tokenization+DebertaV2Tokenizer.prepare_for_tokenization  s-     "::&8%@"2:D~r1   save_directoryfilename_prefixc                 4    U R                   R                  XS9$ )N)rn   )r"   save_pretrained)r%   rm   rn   s      r(   save_vocabulary"DebertaV2Tokenizer.save_vocabulary  s#     .. / = 	=r1   )r"   r   r#   r   r   r   r	   )FFT[CLS][SEP][UNK]rt   [PAD]rs   [MASK]Nr+   )NFF)#__name__
__module____qualname____firstlineno____doc__VOCAB_FILES_NAMESvocab_files_namesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_mapPRETRAINED_INIT_CONFIGURATIONpretrained_init_configuration&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESmax_model_input_sizesr   r   strr   r   propertyr/   r-   r8   r   rC   rJ   rO   rT   r]   rb   re   rk   r   rq   __static_attributes____classcell__)r'   s   @r(   r   r   !   s   /b *!;$A!B  % %#""""""$=A4 #+4S>":4 #4 4l   % %
.c .d3i .4B
.;4 -1;@4B :>E@ 6; :>=(+=)1#=BG*= =r1   r   c                       \ rS rSrSr  SS\\\\4      4S jjr	S r
S rS rS	 rSS
 jrS rSS jrS rS rS rS rS rS rS rS rS rS rS rSS\S\4S jjrSrg) r!   i  a  
Constructs a tokenizer based on [SentencePiece](https://github.com/google/sentencepiece).

Args:
    vocab_file (`str`):
        [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
        contains the vocabulary necessary to instantiate a tokenizer.
    sp_model_kwargs (`dict`, *optional*):
        Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
        SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
        to set:

        - `enable_sampling`: Enable subword regularization.
        - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

          - `nbest_size = {0,1}`: No sampling is performed.
          - `nbest_size > 1`: samples from the nbest_size results.
          - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
            using forward-filtering-and-backward-sampling algorithm.

        - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
          BPE-dropout.
Nr   c                    X l         Xl        Uc  0 OUU l        [        R                  " S0 U R                  D6n[
        R                  R                  U5      (       d  [        U S35      eUR                  U5        UR                  5       n[        U5       Vs0 s H  odR                  U5      U_M     snU l        [        U5       Vs/ s H  odR                  U5      PM     snU l        X@l        g s  snf s  snf )Nz does not exist!r   )r   r	   r   spSentencePieceProcessorr   r   existsFileNotFoundErrorloadGetPieceSizerangerM   r-   ids_to_tokensrF   )r%   r	   r   r   rF   bpe_vocab_sizeis          r(   r   SPMTokenizer.__init__/  s     -$%4%<r/''?$*>*>?ww~~j))#zl2B$CDD))+
 493HI3HammA&)3HI
8=n8MN8M1mmA.8MN  JNs   C2	C7c                 D    U R                   R                  5       nS US'   U$ )NrF   )__dict__r5   )r%   states     r(   __getstate__SPMTokenizer.__getstate__H  s"    ""$er1   c                     Xl         [        U S5      (       d  0 U l        [        R                  " S0 U R                  D6U l        U R
                  R                  U R                  5        g )Nr   r   )r   hasattrr   r   r   rF   Loadr	   )r%   ds     r(   __setstate__SPMTokenizer.__setstate__M  sN     t.//#%D ,,Dt/C/CDdoo&r1   c                 $    U R                  U5      $ r+   )_encode_as_pieces)r%   r:   s     r(   r@   SPMTokenizer.tokenizeW  s    %%d++r1   c                 X    / nU H!  nUR                  U R                  U   5        M#     U$ r+   )appendr   )r%   idsrS   r   s       r(   convert_ids_to_tokens"SPMTokenizer.convert_ids_to_tokensZ  s-    AMM$,,Q/0 r1   c                    Uc+  U R                   R                  U Vs/ s H  oUPM     sn5      $ U R                  U5      nU Vs/ s H  opR                  U5      PM     nnS/[	        U5      -  n	Sn
[        U5       H"  u  p[        U5       H  u  pXU
'   U
S-  n
M     M$     X   nU[	        U5      :  a  X   O
[	        U5      nSR                  XmU 5      nU$ s  snf s  snf )Nr   ra    )rF   decode_piecessplit_to_wordsr@   r,   	enumerater?   )r%   rS   startendraw_texttwordswword_tokenstoken2wordstidr   k
word_startword_endr:   s                   r(   rR   SPMTokenizer.decode`  s    88))f*=f1f*=>>''1E5:;U==+UK;#F+KC!+.%aLDA'($1HC ) / %+J+.V+<{'#e*H775H56DK +> <s   CCc                    XR                   ;  aj  U R                   R                  U5        XR                  ;  a@  [        U R                  5      S-
  U R                  U'   U R                  R                  U5        U R                  U5      $ Nra   )special_tokensr   r-   r,   r   idrH   s     r(   add_special_tokenSPMTokenizer.add_special_tokenq  si    +++&&u-JJ&$'

Oa$7

5!""))%0wwu~r1   c                 L   U(       a  g[        U5      S:X  a  [        [        U5      S   5      (       a  g[        [        U5      S   5      (       a  g[	        [        U5      S   5      (       a  gXR
                  ;   a  gSR                  S5      nUR                  U5      (       + $ )NTra   r   F   ▁utf-8)r,   _is_whitespacelist_is_control_is_punctuationr   rR   
startswith)r%   rI   is_bosr   s       r(   part_of_whole_wordSPMTokenizer.part_of_whole_wordy  s    J!OUA!?!?tE{1~&&4;q>*****$++G4
##J///r1   c                     g)Nrv   r   r.   s    r(   padSPMTokenizer.pad      r1   c                     g)Nrs   r   r.   s    r(   bosSPMTokenizer.bos  r   r1   c                     g)Nrt   r   r.   s    r(   eosSPMTokenizer.eos  r   r1   c                     g)Nru   r   r.   s    r(   unkSPMTokenizer.unk  r   r1   c                     g)Nrw   r   r.   s    r(   maskSPMTokenizer.mask  s    r1   c                      U R                   U   $ r+   )r   )r%   r   s     r(   symSPMTokenizer.sym  s    !!"%%r1   c                 B    XR                   ;   a  U R                   U   $ S$ r   )r-   )r%   r   s     r(   r   SPMTokenizer.id  s    "%"3tzz#::r1   c                 B   [        U5      nU R                  (       a[  U R                  U5      nU Vs/ s H   o0R                  R	                  U[
        S9PM"     nnU VVs/ s H  o3  H  oUPM     M     snn$ U R                  R	                  U[
        S9$ s  snf s  snnf )N)out_type)convert_to_unicoder   _run_split_on_puncrF   encoder   )r%   r:   r   r   piecesps         r(   r   SPMTokenizer._encode_as_pieces  s    !$'++D1E@EF1hhooa#o6FF%1v!q!AqAv1188??4#?66 G1s   'B Bc                    U R                  U5      nSR                  S5      n/ nSnSn[        U5       H  u  pxUR                  U5      (       a-  XV:  a  UR	                  XU 5        UnUR                  US5      n	OUn	 UR                  X5      n
SnUS-   nU[        U5      :  a:  X,   R                  US5      n[        U5      S:  a  OUS-  nU[        U5      :  a  M:  [        U5      S:  a  XXZ ;   a  US-   nM  U
[        U	5      -   nM     Xe:  a  UR	                  XU 5        U$ ! [         a
    US-   n GM  f = f)Nr   r   r   r   ra   )	r   rR   r   r   r   replacerN   r,   	Exception)r%   r:   r   r   r   offsetprev_endr   r   r   spnr   s                r(   r   SPMTokenizer.split_to_words  sJ   ''-$++G4
f%DA||J''$LLv!67!IIj"-$JJq)E#f+o**:r:B2w{FA	 #f+o r7Q;2f#7#aZFQZF+ &2 LLv./  $!$s   ?AD) D)=D))D=<D=c                     [         R                  " SU5      n/ nU H2  n[         R                  " U5      nUS:X  a  M!  UR                  U5        M4     SR	                  U5      $ )z$Strips accents from a piece of text.NFDMnr   )unicodedata	normalizecategoryr   r?   )r%   r:   outputcharcats        r(   _run_strip_accentsSPMTokenizer._run_strip_accents  sY    $$UD1D&&t,Cd{MM$	 
 wwvr1   c                 j   [        U5      nSnSn/ nU[        U5      :  am  X#   n[        U5      (       a  UR                  U/5        SnO.U(       a  UR                  / 5        SnUS   R                  U5        US-  nU[        U5      :  a  Mm  U Vs/ s H  nSR	                  U5      PM     sn$ s  snf )z&Splits punctuation on a piece of text.r   TFra   r   )r   r,   r   r   r?   )r%   r:   charsr   start_new_wordr   r   rA   s           r(   r   SPMTokenizer._run_split_on_punc  s    T
#e*n8Dt$$tf%!%!MM"%!&r
!!$'FA #e*n %++Fq
F+++s   B0r   rn   c                 L   [         [        [         R                  5       5      S      nUb  US-   U-   n[        R                  R                  X5      n[        US5       nUR                  U R                  R                  5       5        S S S 5        U4$ ! , (       d  f       U4$ = f)Nr   -wb)
r~   r   keysr   r   r?   openwriterF   serialized_model_proto)r%   r   rn   filename	full_pathfss         r(   rp   SPMTokenizer.save_pretrained  s    $T*;*@*@*B%CA%FG&&,x7HGGLL0	)T"bHHTXX4467 #} #"}s   *B
B#)r   r   r   r   rF   r-   r	   )FN)r   r   Nrx   r+   )ry   rz   r{   r|   r}   r   r   r   r   r   r   r   r@   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   rp   r   r   r1   r(   r!   r!     s    4 !&=A #+4S>":2
',"0&;7"H	,(C #  r1   r!   c                 p    U S:X  d  U S:X  d  U S:X  d  U S:X  a  g[         R                  " U 5      nUS:X  a  gg)z1Checks whether `chars` is a whitespace character.r<   	
TZsF)r   r   r   r   s     r(   r   r     s=     s{ddlddlddl


t
$C
d{r1   c                     U S:X  d  U S:X  d  U S:X  a  g[         R                  " U 5      nUR                  S5      (       a  gg)z.Checks whether `chars` is a control character.r  r  r  FCT)r   r   r   r  s     r(   r   r     s?     t|tt|tt|


t
$C
~~cr1   c                     [        U 5      nUS:  a  US::  d$  US:  a  US::  d  US:  a  US::  d  US:  a  US::  a  g	[        R                  " U 5      nUR                  S
5      (       a  g	g)z2Checks whether `chars` is a punctuation character.r   /   :   @   [   `   {   ~   TPF)ordr   r   r   )r   cpr   s      r(   r   r     sg    	TB
 	bR2X28b"HrrSyR3Y


t
$C
~~cr1   c                     [        U [        5      (       a  U $ [        U [        5      (       a  U R                  SS5      $ [	        S[        U 5       35      e)zGConverts `text` to Unicode (if it's not already), assuming utf-8 input.r   ignorezUnsupported string type: )
isinstancer   bytesrR   r    type)r:   s    r(   r   r     sI    $	D%	 	 {{7H--4T$ZLABBr1   )r}   r   r   typingr   r   r   r   r   sentencepiecer   transformers.tokenization_utilsr   r   r   r   r~   r   r!   r   r   r   r   r   r1   r(   <module>r(     sq    h 	  3 3  ?*B/ )+ & " !;/ r=, r=jZ Zz		 Cr1   