
    9i)b                     J    S SK r S SKrS SKrS SKrS SKrS SKr " S S\5      rg)    Nc                      \ rS rSrSr        SS jrS rS rS rS r	S	 r
S
 rS rS r\S 5       r\S 5       rSS jr\S 5       r\    SS j5       r\       SS j5       r\    SS j5       rS rS rS rS rS rSrg)Vocab   a1  
The class used to convert between tokens and ids. It also includes some
store/load functions.

Args:
    counter (collections.Counter, optional): A Counter instance describes
        the tokens and their frequencies. Its keys will be indexed according
        to the order of frequency sorting to construct mapping relationship.
        If None, `token_to_idx` must be provided as the mapping relationship.
        Default: None.
    max_size (int, optional): Max size of vocab, not including special tokens.
        Default: None.
    min_freq (int, optional): Ignore tokens whose frequencies are less than
        `min_freq`. Default: 1.
    token_to_idx (dict, optional): A dict specifies the mapping relationship
        between tokens and indices to be used. If provided, adjust the tokens
        and indices mapping according to it. If None, counter must be provided.
        Default: None.
    unk_token (str, optional): Special token for unknown token. If no need,
        it also could be None. Default: None.
    pad_token (str, optional): Special token for padding token. If no need,
        it also could be None. Default: None.
    bos_token (str, optional): Special token for bos token. If no need, it
        also could be None. Default: None.
    eos_token (str, optional): Special token for eos token. If no need, it
        lso could be None. Default: None.

    kwargs (dict): Keyword arguments ending with `_token`. It can be used
        to specify further special tokens that will be exposed as attribute
        of the vocabulary and associated with an index.
Nc	                 :  ^ ^^ ST4SU4SU4SU44n
U
 H	  u  pXU'   M     / nU	R                  5       n[        U5      nU HU  nUR                  S5      (       d  [        SR	                  U5      5      eX   nUc  M<  UU;  d  MD  UR                  U5        MW     Uc  U(       d   S5       eU H  nUU;   a  M   SR	                  U5      5       e   UT l        UR                  5        VVs0 s H	  u  nnUU_M     snnT l        T(       aI  T R                  T   m[        R                  " U4S	 j5      T l        T R                  R                  U5        O[        U5       VVs0 s H	  u  nnUU_M     snnT l        [        R                  " 5       T l        T R                  R                  S
 T R                  R                  5        5       5        T R                  XX#5        U(       a  T R                  U5        T(       a  U U4S jT R                  l        U	T l        U	R                  5        H`  u  nnUR#                  S5      (       a  [        S5      e[%        T U5      (       a  [        SR	                  UU5      5      e['        T UU5        Mb     g s  snnf s  snnf )N	unk_token	pad_token	bos_token	eos_token_tokenzc{} is invalid. Only keyword arguments that end in '_token' are supported to declare special tokens.z4token_to_idx should not be None when counter is Nonez{} is not in token_to_idxc                     > T $ N )	unk_indexs   o/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/paddlex/inference/models/common/tokenizer/vocab.py<lambda> Vocab.__init__.<locals>.<lambda>j   s    Y    c              3   ,   #    U  H
  u  pX!4v   M     g 7fr   r   ).0idxtokens      r   	<genexpr>!Vocab.__init__.<locals>.<genexpr>q   s      &/I/Is   c                  "   > T R                   T   $ r   _token_to_idx)selfr   s   r   r   r   x   s    T=O=O>r   _zIt is not allowed to use identifiers starting with underscore. In Python identifier names beginning with underscore are internal.zJvocab.{} already exists. Please choose a different identifier for token {})keyssortedendswith
ValueErrorformatappendr   items_idx_to_tokencollectionsdefaultdictupdate	enumerate_index_counter_keys+_sort_index_according_to_user_specificationdefault_factory_identifiers_to_tokens
startswithhasattrsetattr)r   countermax_sizemin_freqtoken_to_idxr   r   r	   r
   kwargscombsnamevaluespecial_tokensspecial_iterspecial_token_namespecial_tokenr   r   
identifierr   s   `    `              @r   __init__Vocab.__init__9   s    )$)$)$)$	
 !KD 4L !{{}l+".%..x88 1178J1K  #6M(].-P%%m4 #/ ?W!WW<!/!\1E.55mDE1 "0 ".D?K?Q?Q?S!T?S#u*?S!TD ..y9	%0%<%<=N%O""")),7 >G~=V"=V'9sM]"=V"D "-!8!8!:D%% &/3/A/A/G/G/I&  $$WhQ@@N6""2
 '-#!'J$$S)) / 
 tZ(( HHN"EI  D*e, "0/ "U"s   )J!Jc           	         [        UR                  5       S S9nUR                  S SS9  [        U5      nUc  S OU[	        U5      -   nU H  u  pgXt:  d  [	        U R
                  5      U:X  a    g Xb;  d  M,  UU R
                  [        [        U R
                  R                  5       5      S/-   5      S-   '   [        U R
                  R                  5       5      U R                  U'   M     g )Nc                     U S   $ )Nr   r   xs    r   r   +Vocab._index_counter_keys.<locals>.<lambda>   s    AaDr   )keyc                     U S   $ )N   r   rC   s    r   r   rE      s    qtr   T)rF   reverserH   )
r    r%   sortsetlenr&   maxlistr   r   )r   r2   r:   r3   r4   token_freqsr   freqs           r   r+   Vocab._index_counter_keys   s    W]]_.A^T: ^,#+4C<O1O&KE#d&8&8"9X"E* ""3tD,>,>,C,C,E'F"'M#NQR#RS -00B0B0G0G0I,J""5) 'r   c                    [        UR                  5       5      R                  U R                  R                  5       5      (       d  [	        S5      e[        [        UR                  5       5      5      [        U5      :w  a  [	        S5      e[        UR                  5       5      S:  d0  [        UR                  5       5      [        U R                  5      :  a-  [	        SR                  [        U R                  5      5      5      eUR                  5        H[  u  p#U R                  U   nU R                  U   nX0R                  U'   X@R                  U'   XPR                  U'   X R                  U'   M]     g )Nz`User-specified token_to_idx mapping can only contain tokens that will be part of the vocabulary.z3User-specified indices must not contain duplicates.r   zUser-specified indices must not be < 0 or >= the number of tokens that will be in the vocabulary. The current vocab contains {}tokens.)rL   r   issubsetr5   r"   rM   valuesminrN   r#   r%   idx_to_token)r   r5   r   new_idxold_idxousted_tokens         r   r,   1Vocab._sort_index_according_to_user_specification   sD   <$$&'001B1B1G1G1IJJ>  s<&&()*c,.??RSS|""$%)S1D1D1F-G3L
 .
  &T%6%6!78  +002NE''.G,,W5L'.e$.5l+)5g&).g& 3r   c                    Sn[        U[        [        [        R                  45      (       d  U/nSn[        U[        [        45      (       a  [        R
                  " U5      n[        U[        R                  5      (       aF  [        UR                  5      S:  a-  [        SR                  [        UR                  5      5      5      e/ nU Hh  n[        U[        [        R                  45      (       d!  [        R                  " S5        [        U5      n UR                  U R                  U   5        Mj     U(       a  US   $ U$ ! [          a    [        SR                  U5      5      ef = f)u  
Maps the input indices to token list.

Args:
    indices (int|list[int]|tuple[int]|numpy.ndarray): The input indice(s) for mapping.
        Must be an `int` or 1D `list[int]`|`tuple[int]`|`numpy.ndarray`.

Returns:
    str|list[str]: Obtained token(s). If `indices` is an integer, it
    will return a str. If `indices` is a list/tuple of integers, it will
    return a list of str.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')
        tokens = vocab.to_tokens([0, 1, 2, 3])
        print(tokens)
        # ['[PAD]', '[UNK]', '一斤三', '意面屋']
FTrH   zEToken indices is invalid. Expected 1D array, but received {}D array. zfThe type of `to_tokens()`'s input `indices` is not `int` which will be forcibly transferred to `int`. z4Token index {} in the provided `indices` is invalid.r   )
isinstancerO   tuplenpndarrayasarrayrM   shaper"   r#   intintegerwarningswarnr$   r&   KeyError)r   indices	to_reducetokensr   s        r   	to_tokensVocab.to_tokens   s1   : 	'D%#<==iGIge}--jj)Gg

,,W]]1Ca1GW^^&  CcC#455| #hd0056  &vay161   JQQRUV s   E%E+c                 
    X   $ )uc  
Maps the input tokens into indices.

Args:
    tokens (str|list[str]|tuple[str], optional): The input token(s) for
        mapping.

Returns:
    int|list[int]: Obationed indice(s). If `tokens` is a str, it will
    return an integer. If `tokens` is a list/tuple of str, it will
    return a list of integers.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')
        tokens = vocab.to_indices(['[PAD]', '[UNK]', '一斤三', '意面屋'])
        print(tokens)
        # [0, 1, 2, 3]
r   r   rj   s     r   
to_indicesVocab.to_indices   s    : |r   c                 @   [        U[        [        45      (       d7  XR                  ;   a  U R                  U   $ U R                  U R                     $ U Vs/ s H:  nX R                  ;   a  U R                  U   OU R                  U R                     PM<     sn$ s  snf r   )r]   rO   r^   r   r   )r   rj   r   s      r   __getitem__Vocab.__getitem__  s    &4-00 /// ""6* ''7 $ $E  2 22 &&u-++DNN;< $  s   ABc                 ,    [        U R                  5      $ r   )rM   r&   r   s    r   __len__Vocab.__len__'  s    4%%&&r   c                     XR                   ;   $ r   r   )r   r   s     r   __contains__Vocab.__contains__*  s    ****r   c                 
    X   $ )z}
Maps the input tokens into indices. Its function is the same as the
:meth:`to_indices` method.

See detail at `to_indices`.
r   rn   s     r   __call__Vocab.__call__-  s     |r   c                     U R                   $ r   )r&   ru   s    r   rW   Vocab.idx_to_token6       !!!r   c                     U R                   $ r   r   ru   s    r   r5   Vocab.token_to_idx;  r   r   c                 h   0 n[        U R                  5      US'   [        U R                  5      US'   U R                  US'   U R                  US'   [
        R                  " U5      nU(       a2  [        R                  " USSS9 nUR                  U5        SSS5        U$ U$ ! , (       d  f       U$ = f)	a  
Summarizes some information of vocab as JSON string. If path is gaven,
the JSON string will be saved into files. The JSON string and the saved
file all can be used to reconstruct the :class:`Vocab` by calling
:meth:`from_json` method.

Args:
    path (str, optional): The path to save JSON string. If None, the
        JSON will not be saved. Default: None.

Returns:
    str: The JSON string including information of vocab.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')
        json_str = vocab.to_json(path='./vocab.json')
rW   r5   r   identifiers_to_tokenswutf-8encodingN)
dictrW   r5   r   r.   jsondumpsioopenwrite)r   path
vocab_dictjson_strfs        r   to_jsonVocab.to_json@  s    8 
%)$*;*;%<
>"%)$*;*;%<
>""&..
;.2.I.I
*+::j)sW5! 6x 65s   B""
B1c                    [         R                  R                  U5      (       a6  [        R                  " USSS9 n[
        R                  " U5      nSSS5        O[
        R                  " U5      nWR                  S5      nUR                  S5      nUR                  S[        5       5      nSU;   a  US	 U " S	SUUS.UD6nU$ ! , (       d  f       Na= f)
a  
Loads :class:`Vocab` from JSON string or JSON file, which is gotten by
calling :meth:`to_json` method.

Args:
    json_str (str): JSON string or file path of JSON string.

Returns:
    Vocab: An instance of :class:`Vocab` generated from information
    contained in JSON string.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')
        json_str = vocab.to_json(path='./vocab.json')

        vocab1 = Vocab.from_json(json_str)
        vocab2 = Vocab.from_json('./vocab.json')
        print(len(vocab), len(vocab1), len(vocab2))
        # 1256608 1256608 1256608
rr   r   Nr5   r   r   )r2   r5   r   r   )
osr   isfiler   r   r   loadloadsgetr   )clsr   r   r   r5   r   r   vocabs           r   	from_jsonVocab.from_jsong  s    @ 77>>(##39Q!YYq\
 :9 H-J!~~n5NN;/	 */F O//%k2 
%
 $	
  :9s   C
Cc           
      $    U " SSUUUUUS.UD6nU$ )a  
Builds the :class:`Vocab` from a dict.

Args:
    token_to_idx (dict): A dict describes the mapping relationship between
        tokens and indices.
    unk_token (str, optional): The special token for unknown token. If
        no need, it also could be None. Default: None.
    pad_token (str, optional): The special token for padding token. If
        no need, it also could be None. Default: None.
    bos_token (str, optional): The special token for bos token. If no
        need, it also could be None. Default: None.
    eos_token (str, optional): The special token for eos token. If no
        need, it also could be None. Default: None.

    kwargs (dict): Keyword arguments ending with `_token`. It can be
        used to specify further special tokens that will be exposed as
        attribute of the vocabulary and associated with an index.

Returns:
    Vocab: An instance of :class:`Vocab` generated from the given dict
    and special tokens.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')

        vocab1 = Vocab.from_dict(vocab.token_to_idx)
        print(len(vocab), len(vocab.token_to_idx), len(vocab1))
        # 1256608 1256608 1256608
N)r2   r5   r   r   r	   r
   r   r   )r   r5   r   r   r	   r
   r6   r   s           r   	from_dictVocab.from_dict  s7    d  
%
 
 r   c                     [         R                  " 5       n	U  H  n
U	R                  U
5        M     [        U	4UUUUUUUS.UD6nU$ )a  
Builds the :class:`Vocab` according to given iterator and other
information. Firstly, iterate over the `iterator` to construct a
:class:`collections.Counter` and used to init the as  :class:`Vocab`.

Args:
    iterator (collections.Iterable): Iterator of tokens. Each element
        should be a list of tokens if wordlevel vocab is needed.
    max_size (int, optional): The max size of vocab, not including
        special tokens. Default: None.
    min_freq (int, optional): Ignore tokens whose frequencies are less
        than `min_freq`. Default: 1.
    token_to_idx (dict, optional): A dict specifies the mapping
        relationship between tokens and indices to be used. If provided,
        adjust the tokens and indices mapping according to it. If None,
        counter must be provided. Default: None.
    unk_token (str, optional): The special token for unknown token
        '<unk>'. If no need, it also could be None. Default: None.
    pad_token (str, optional): The special token for padding token
        '<pad>'. If no need, it also could be None. Default: None.
    bos_token (str, optional): The special token for bos token '<bos>'.
        If no need, it also could be None. Default: None.
    eos_token (str, optional): The special token for eos token '<eos>'.
        If no need, it also could be None. Default: None.

    kwargs (dict): Keyword arguments ending with `_token`. It can be
        used to specify further special tokens that will be exposed as
        attribute of the vocabulary and associated with an index.

Returns:
    Vocab: An instance of :class:`Vocab` generated from given iterator
    and other informations.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')

        vocab1 = Vocab.build_vocab([list(vocab.token_to_idx.keys())])
        print(len(vocab), len(vocab1))
        # 1256608 1256608
)r3   r4   r5   r   r   r	   r
   )r'   Counterr)   r   )iteratorr3   r4   r5   r   r   r	   r
   r6   r2   rj   r   s               r   build_vocabVocab.build_vocab  sa    | %%'FNN6" 

%

 

 r   c                    0 n[         R                  " U SSS9 n[        U5       H#  u  pU	R                  S5      n
[	        U5      Xj'   M%     SSS5        [
        R                  " U4UUUUS.UD6nU$ ! , (       d  f       N,= f)a  
Builds the :class:`Vocab` from a file reserving all tokens by calling
:meth:`Vocab.from_dict` method. The file contains a token per line, and
the line index would be the index of corresponding token.

Args:
    filepath (str): the path of file to construct vocabulary.
    unk_token (str, optional): special token for unknown token. If no
        need, it also could be None. Default: None.
    pad_token (str, optional): special token for padding token. If no
        need, it also could be None. Default: None.
    bos_token (str, optional): special token for bos token. If no need,
        it also could be None. Default: None.
    eos_token (str, optional): special token for eos token. If no need,
        it also could be None. Default: None.

    kwargs (dict): Keyword arguments ending with `_token`. It can be
        used to specify further special tokens that will be exposed as
        attribute of the vocabulary and associated with an index.

Returns:
    Vocab: An instance of :class:`Vocab` generated from the given file.

Example:
    .. code-block:: python

        from paddlenlp.data import Vocab
        # The vocab file. The sample file can be downloaded firstly.
        # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
        vocab_file_path = './senta_word_dict.txt'
        # Initialize the Vocab
        vocab = Vocab.load_vocabulary(
            vocab_file_path,
            unk_token='[UNK]',
            pad_token='[PAD]')
        print(len(vocab))
        # 1256608
r   r   r   
N)r   r   r	   r
   )r   r   r*   rstriprc   r   r   )filepathr   r   r	   r
   r6   r5   r   indexliner   r   s               r   load_vocabularyVocab.load_vocabulary$  s    ^ WWXsW5(|D)&)%j#  , 6 

 
  65s   3A22
B c                     [        US5       n[        [        U R                  5      5       H$  nUR	                  U R                  U   S-   5        M&     SSS5        g! , (       d  f       g= f)z
Save the :class:`Vocab` to a specific file. Can be reloaded by calling `load_vocabulary`.

Args:
    filepath (str): the path of file to save vocabulary.
r   r   N)r   rangerM   r&   r   )r   r   r   r   s       r   save_vocabularyVocab.save_vocabularyb  sR     (C AS!3!345**3/$67 6 !  s   AA
A+c                 f    U R                   b  U R                  U R                      $ U R                   $ r   )r   r   ru   s    r   get_unk_token_idVocab.get_unk_token_idm  5     ~~) t~~.	
 	
r   c                 f    U R                   b  U R                  U R                      $ U R                   $ r   )r	   r   ru   s    r   get_bos_token_idVocab.get_bos_token_idt  r   r   c                 f    U R                   b  U R                  U R                      $ U R                   $ r   )r
   r   ru   s    r   get_eos_token_idVocab.get_eos_token_id{  r   r   c                 f    U R                   b  U R                  U R                      $ U R                   $ r   )r   r   ru   s    r   get_pad_token_idVocab.get_pad_token_id  r   r   )r.   r&   r   )NNrH   NNNNNr   )NNNN)NrH   NNNNN)__name__
__module____qualname____firstlineno____doc__r?   r+   r,   rk   ro   rr   rv   ry   r|   propertyrW   r5   r   classmethodr   r   staticmethodr   r   r   r   r   r   r   __static_attributes__r   r   r   r   r      s#   D S-jK"/8:2x>"'+ " " " "%N / /b  : :x  K KZ  ; ;z	8



r   r   )	r'   r   r   r   re   numpyr_   objectr   r   r   r   <module>r      s'     	  	  o	
F o	
r   