a
    SicX                     @   s   d Z ddlZddlZddlZddlZddlZddlmZ edddd	Z	ed
dddZ
eddddZedG dd deZeddd ZdS )a  Utilities for text input preprocessing.

Deprecated: `tf.keras.preprocessing.text` APIs are not recommended for new code.
Prefer `tf.keras.utils.text_dataset_from_directory` and
`tf.keras.layers.TextVectorization` which provide a more efficient approach
for preprocessing text input. For an introduction to these APIs, see
the [text loading tutorial]
(https://www.tensorflow.org/tutorials/load_data/text)
and [preprocessing layer guide]
(https://www.tensorflow.org/guide/keras/preprocessing_layers).
    N)keras_exportz.keras.preprocessing.text.text_to_word_sequence!!"#$%&()*+,-./:;<=>?@[\]^_`{|}~	
T c                    sJ   |r|   }  fdd|D }t|}| |} |  }dd |D S )a  Converts a text to a sequence of words (or tokens).

    Deprecated: `tf.keras.preprocessing.text.text_to_word_sequence` does not
    operate on tensors and is not recommended for new code. Prefer
    `tf.strings.regex_replace` and `tf.strings.split` which provide equivalent
    functionality and accept `tf.Tensor` input. For an overview of text handling
    in Tensorflow, see the [text loading tutorial]
    (https://www.tensorflow.org/tutorials/load_data/text).

    This function transforms a string of text into a list of words
    while ignoring `filters` which include punctuations by default.

    >>> sample_text = 'This is a sample sentence.'
    >>> tf.keras.preprocessing.text.text_to_word_sequence(sample_text)
    ['this', 'is', 'a', 'sample', 'sentence']

    Args:
        input_text: Input text (string).
        filters: list (or concatenation) of characters to filter out, such as
            punctuation. Default: ``'!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n'``,
              includes basic punctuation, tabs, and newlines.
        lower: boolean. Whether to convert the input to lowercase.
        split: str. Separator for word splitting.

    Returns:
        A list of words (or tokens).
    c                    s   i | ]
}| qS  r   ).0csplitr   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/preprocessing/text.py
<dictcomp>L       z)text_to_word_sequence.<locals>.<dictcomp>c                 S   s   g | ]}|r|qS r   r   )r   ir   r   r
   
<listcomp>Q   r   z)text_to_word_sequence.<locals>.<listcomp>)lowerstr	maketrans	translater	   )
input_textfiltersr   r	   Ztranslate_dictZtranslate_mapseqr   r   r
   text_to_word_sequence'   s    "


r   z keras.preprocessing.text.one_hotc              	   C   s   t | |t||||dS )a
  One-hot encodes a text into a list of word indexes of size `n`.

    Deprecated: `tf.keras.text.preprocessing.one_hot` does not operate on
    tensors and is not recommended for new code. Prefer
    `tf.keras.layers.Hashing` with `output_mode='one_hot'` which provides
    equivalent functionality through a layer which accepts `tf.Tensor` input.
    See the [preprocessing layer guide]
    (https://www.tensorflow.org/guide/keras/preprocessing_layers) for an
    overview of preprocessing layers.

    This function receives as input a string of text and returns a
    list of encoded integers each corresponding to a word (or token)
    in the given input string.

    Args:
        input_text: Input text (string).
        n: int. Size of vocabulary.
        filters: list (or concatenation) of characters to filter out, such as
          punctuation. Default:
          ```
          '!"#$%&()*+,-./:;<=>?@[\]^_`{|}~\t\n
          ```,
          includes basic punctuation, tabs, and newlines.
        lower: boolean. Whether to set the text to lowercase.
        split: str. Separator for word splitting.
        analyzer: function. Custom analyzer to split the text

    Returns:
        List of integers in `[1, n]`. Each integer encodes a word
        (unicity non-guaranteed).
    )hash_functionr   r   r	   analyzer)hashing_trickhash)r   nr   r   r	   r   r   r   r
   one_hotT   s    (r   z&keras.preprocessing.text.hashing_trickc                    sT    du rt  n dkrdd  |du r8t| |||d}n|| } fdd|D S )a  Converts a text to a sequence of indexes in a fixed-size hashing space.

    Deprecated: `tf.keras.text.preprocessing.hashing_trick` does not operate on
    tensors and is not recommended for new code. Prefer
    `tf.keras.layers.Hashing` which provides equivalent functionality through a
    layer which accepts `tf.Tensor` input. See the [preprocessing layer guide](
    https://www.tensorflow.org/guide/keras/preprocessing_layers) for an
    overview of preprocessing layers.

    Args:
        text: Input text (string).
        n: Dimension of the hashing space.
        hash_function: defaults to python `hash` function, can be 'md5' or
            any function that takes in input a string and returns a int.
            Note that 'hash' is not a stable hashing function, so
            it is not consistent across different runs, while 'md5'
            is a stable hashing function.
        filters: list (or concatenation) of characters to filter out, such as
            punctuation. Default: ``!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``,
            includes basic punctuation, tabs, and newlines.
        lower: boolean. Whether to set the text to lowercase.
        split: str. Separator for word splitting.
        analyzer: function. Custom analyzer to split the text

    Returns:
        A list of integer word indices (unicity non-guaranteed).
        `0` is a reserved index that won't be assigned to any word.
        Two or more words may be assigned to the same index, due to possible
        collisions by the hashing function.
        The [probability](
            https://en.wikipedia.org/wiki/Birthday_problem#Probability_table)
        of a collision is in relation to the dimension of the hashing space and
        the number of distinct objects.
    Nmd5c                 S   s   t t|   dS )N   )inthashlibr   encode	hexdigest)wr   r   r
   <lambda>   r   zhashing_trick.<locals>.<lambda>r   r   r	   c                    s    g | ]} |d   d  qS )   r   )r   r#   r   r   r   r
   r      r   z!hashing_trick.<locals>.<listcomp>)r   r   )textr   r   r   r   r	   r   r   r   r'   r
   r      s    ,r   z"keras.preprocessing.text.Tokenizerc                   @   sn   e Zd ZdZdddZd	d
 Zdd Zdd Zdd Zdd Z	dd Z
dddZd ddZdd Zdd ZdS )!	Tokenizerag  Text tokenization utility class.

    Deprecated: `tf.keras.preprocessing.text.Tokenizer` does not operate on
    tensors and is not recommended for new code. Prefer
    `tf.keras.layers.TextVectorization` which provides equivalent functionality
    through a layer which accepts `tf.Tensor` input. See the
    [text loading tutorial](https://www.tensorflow.org/tutorials/load_data/text)
    for an overview of the layer and text handling in tensorflow.

    This class allows to vectorize a text corpus, by turning each
    text into either a sequence of integers (each integer being the index
    of a token in a dictionary) or into a vector where the coefficient
    for each token could be binary, based on word count, based on tf-idf...

    By default, all punctuation is removed, turning the texts into
    space-separated sequences of words
    (words maybe include the `'` character). These sequences are then
    split into lists of tokens. They will then be indexed or vectorized.

    `0` is a reserved index that won't be assigned to any word.

    Args:
        num_words: the maximum number of words to keep, based
            on word frequency. Only the most common `num_words-1` words will
            be kept.
        filters: a string where each element is a character that will be
            filtered from the texts. The default is all punctuation, plus
            tabs and line breaks, minus the `'` character.
        lower: boolean. Whether to convert the texts to lowercase.
        split: str. Separator for word splitting.
        char_level: if True, every character will be treated as a token.
        oov_token: if given, it will be added to word_index and used to
            replace out-of-vocabulary words during text_to_sequence calls
        analyzer: function. Custom analyzer to split the text.
            The default analyzer is text_to_word_sequence
    Nr   Tr   Fc           
      K   s   d|v rt d |d}|dd}	|r<tdt| t | _tt	| _
|| _|| _|| _|| _|	| _|| _|| _tt	| _i | _i | _|| _d S )Nnb_wordszDThe `nb_words` argument in `Tokenizer` has been renamed `num_words`.document_countr   z Unrecognized keyword arguments: )warningswarnpop	TypeErrorr   collectionsOrderedDictword_countsdefaultdictr   	word_docsr   r	   r   	num_wordsr+   
char_level	oov_token
index_docs
word_index
index_wordr   )
selfr5   r   r   r	   r6   r7   r   kwargsr+   r   r   r
   __init__   s*    

zTokenizer.__init__c                 C   s  |D ]}|  j d7  _ | js&t|trT| jrNt|trFdd |D }n| }|}n,| jdu rvt|| j| j| jd}n
| |}|D ],}|| j	v r| j	|  d7  < qd| j	|< qt
|D ]}| j|  d7  < qqt| j	 }|jdd dd	 | jdu rg }n| jg}|d
d |D  tt|ttdt|d | _dd | j D | _t| j D ]\}}|| j| j| < qhdS )a  Updates internal vocabulary based on a list of texts.

        In the case where texts contains lists,
        we assume each entry of the lists to be a token.

        Required before using `texts_to_sequences` or `texts_to_matrix`.

        Args:
            texts: can be a list of strings,
                a generator of strings (for memory-efficiency),
                or a list of list of strings.
        r&   c                 S   s   g | ]}|  qS r   r   r   Z	text_elemr   r   r
   r     r   z*Tokenizer.fit_on_texts.<locals>.<listcomp>Nr%   c                 S   s   | d S )Nr&   r   )xr   r   r
   r$   7  r   z(Tokenizer.fit_on_texts.<locals>.<lambda>T)keyreversec                 s   s   | ]}|d  V  qdS )r   Nr   )r   Zwcr   r   r
   	<genexpr>=  r   z)Tokenizer.fit_on_texts.<locals>.<genexpr>c                 S   s   i | ]\}}||qS r   r   )r   r#   r   r   r   r
   r   D  r   z*Tokenizer.fit_on_texts.<locals>.<dictcomp>)r+   r6   
isinstancelistr   r   r   r   r	   r2   setr4   itemssortr7   extenddictziprangelenr9   r:   r8   )r;   textsr(   r   r#   ZwcountsZ
sorted_vocr   r   r   r
   fit_on_texts  sD    



zTokenizer.fit_on_textsc                 C   sD   |  j t|7  _ |D ](}t|}|D ]}| j|  d7  < q&qdS )a  Updates internal vocabulary based on a list of sequences.

        Required before using `sequences_to_matrix`
        (if `fit_on_texts` was never called).

        Args:
            sequences: A list of sequence.
                A "sequence" is a list of integer word indices.
        r&   N)r+   rM   rF   r8   )r;   	sequencesr   r   r   r   r
   fit_on_sequencesI  s
    
zTokenizer.fit_on_sequencesc                 C   s   t | |S )aG  Transforms each text in texts to a sequence of integers.

        Only top `num_words-1` most frequent words will be taken into account.
        Only words known by the tokenizer will be taken into account.

        Args:
            texts: A list of texts (strings).

        Returns:
            A list of sequences.
        )rE   texts_to_sequences_generator)r;   rN   r   r   r
   texts_to_sequencesY  s    zTokenizer.texts_to_sequencesc           	      c   s   | j }| j| j}|D ]}| js,t|trZ| jrTt|trLdd |D }n| }|}n,| jdu r|t	|| j
| j| jd}n
| |}g }|D ]X}| j|}|dur|r||kr|dur|| q|| q| jdur|| q|V  qdS )a  Transforms each text in `texts` to a sequence of integers.

        Each item in texts can also be a list,
        in which case we assume each item of that list to be a token.

        Only top `num_words-1` most frequent words will be taken into account.
        Only words known by the tokenizer will be taken into account.

        Args:
            texts: A list of texts (strings).

        Yields:
            Yields individual sequences.
        c                 S   s   g | ]}|  qS r   r>   r?   r   r   r
   r   |  r   z:Tokenizer.texts_to_sequences_generator.<locals>.<listcomp>Nr%   )r5   r9   getr7   r6   rD   rE   r   r   r   r   r	   append)	r;   rN   r5   oov_token_indexr(   r   vectr#   r   r   r   r
   rR   g  s8    



z&Tokenizer.texts_to_sequences_generatorc                 C   s   t | |S )aR  Transforms each sequence into a list of text.

        Only top `num_words-1` most frequent words will be taken into account.
        Only words known by the tokenizer will be taken into account.

        Args:
            sequences: A list of sequences (list of integers).

        Returns:
            A list of texts (strings)
        )rE   sequences_to_texts_generator)r;   rP   r   r   r
   sequences_to_texts  s    zTokenizer.sequences_to_textsc                 c   s   | j }| j| j}|D ]}g }|D ]d}| j|}|durn|rb||krb|durl|| j|  q|| q$| jdur$|| j|  q$d|}|V  qdS )a  Transforms each sequence in `sequences` to a list of texts(strings).

        Each sequence has to a list of integers.
        In other words, sequences should be a list of sequences

        Only top `num_words-1` most frequent words will be taken into account.
        Only words known by the tokenizer will be taken into account.

        Args:
            sequences: A list of sequences.

        Yields:
            Yields individual texts.
        Nr   )r5   r9   rT   r7   r:   rU   join)r;   rP   r5   rV   r   rW   numwordr   r   r
   rX     s    

z&Tokenizer.sequences_to_texts_generatorbinaryc                 C   s   |  |}| j||dS )zConvert a list of texts to a Numpy matrix.

        Args:
            texts: list of strings.
            mode: one of "binary", "count", "tfidf", "freq".

        Returns:
            A Numpy matrix.
        )mode)rS   sequences_to_matrix)r;   rN   r^   rP   r   r   r
   texts_to_matrix  s    

zTokenizer.texts_to_matrixc                 C   sT  | j s&| jrt| jd }q,tdn| j }|dkrB| jsBtdtt||f}t|D ]\}}|sjq\t	t
}|D ]}||krqx||  d7  < qxt| D ]\}}	|dkr|	|| |< q|dkr|	t| || |< q|dkrd|| |< q|dkrBdt|	 }
td| jd| j|d   }|
| || |< qtd	|qq\|S )
a  Converts a list of sequences into a Numpy matrix.

        Args:
            sequences: list of sequences
                (a sequence is a list of integer word indices).
            mode: one of "binary", "count", "tfidf", "freq"

        Returns:
            A Numpy matrix.

        Raises:
            ValueError: In case of invalid `mode` argument,
                or if the Tokenizer requires to be fit to sample data.
        r&   zKSpecify a dimension (`num_words` argument), or fit on some text data first.Ztfidfz7Fit the Tokenizer on some data before using tfidf mode.countfreqr]   r   zUnknown vectorization mode:)r5   r9   rM   
ValueErrorr+   npzeros	enumerater0   r3   r   rE   rG   logr8   rT   )r;   rP   r^   r5   r@   r   r   countsjr   tfZidfr   r   r
   r_     sJ    

zTokenizer.sequences_to_matrixc                 C   sh   t | j}t | j}t | j}t | j}t | j}| j| j| j	| j
| j| j| j|||||dS )a:  Returns the tokenizer configuration as Python dictionary.

        The word count dictionaries used by the tokenizer get serialized
        into plain JSON, so that the configuration can be read by other
        projects.

        Returns:
            A Python dictionary with the tokenizer configuration.
        )r5   r   r   r	   r6   r7   r+   r2   r4   r8   r:   r9   )jsondumpsr2   r4   r8   r9   r:   r5   r   r   r	   r6   r7   r+   )r;   Zjson_word_countsZjson_word_docsZjson_index_docsZjson_word_indexZjson_index_wordr   r   r
   
get_config  s$    
zTokenizer.get_configc                 K   s(   |   }| jj|d}tj|fi |S )a  Returns a JSON string containing the tokenizer configuration.

        To load a tokenizer from a JSON string, use
        `keras.preprocessing.text.tokenizer_from_json(json_string)`.

        Args:
            **kwargs: Additional keyword arguments
                to be passed to `json.dumps()`.

        Returns:
            A JSON string containing the tokenizer configuration.
        )
class_nameconfig)rm   	__class____name__rk   rl   )r;   r<   ro   tokenizer_configr   r   r
   to_json-  s
    zTokenizer.to_json)Nr   Tr   FNN)r]   )r]   )rq   
__module____qualname____doc__r=   rO   rQ   rS   rR   rY   rX   r`   r_   rm   rs   r   r   r   r
   r)      s&   '       
$<0 

<r)   z,keras.preprocessing.text.tokenizer_from_jsonc           	      C   s   t | }|d}t |d}t |d}t |d}dd | D }t |d}dd | D }t |d	}tf i |}||_||_||_||_	||_
|S )
ar  Parses a JSON tokenizer configuration and returns a tokenizer instance.

    Deprecated: `tf.keras.preprocessing.text.Tokenizer` does not operate on
    tensors and is not recommended for new code. Prefer
    `tf.keras.layers.TextVectorization` which provides equivalent functionality
    through a layer which accepts `tf.Tensor` input. See the
    [text loading tutorial](https://www.tensorflow.org/tutorials/load_data/text)
    for an overview of the layer and text handling in tensorflow.

    Args:
        json_string: JSON string encoding a tokenizer configuration.

    Returns:
        A Keras Tokenizer instance
    ro   r2   r4   r8   c                 S   s   i | ]\}}t ||qS r   r   r   kvr   r   r
   r   Z  r   z'tokenizer_from_json.<locals>.<dictcomp>r:   c                 S   s   i | ]\}}t ||qS r   rw   rx   r   r   r
   r   \  r   r9   )rk   loadsrT   r.   rG   r)   r2   r4   r8   r9   r:   )	json_stringrr   ro   r2   r4   r8   r:   r9   	tokenizerr   r   r
   tokenizer_from_jsonB  s     

r~   )r   Tr   )r   Tr   N)Nr   Tr   N)rv   r0   r    rk   r,   numpyrd    tensorflow.python.util.tf_exportr   r   r   r   objectr)   r~   r   r   r   r
   <module>   s>      ,    2     :   