a
    Sic,                     @   s   d Z ddlm  mZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ ejZejZejZejZed	d
G dd dejZdS )z"Keras hashing preprocessing layer.    N)backend)
base_layer)base_preprocessing_layer)preprocessing_utils)layer_utils)keras_exportzkeras.layers.Hashingz/keras.layers.experimental.preprocessing.Hashingc                       sN   e Zd ZdZd fdd	Zdd Zd	d
 Zdd Zdd Z fddZ	  Z
S )Hashinga  A preprocessing layer which hashes and bins categorical features.

    This layer transforms categorical inputs to hashed output. It element-wise
    converts a ints or strings to ints in a fixed range. The stable hash
    function uses `tensorflow::ops::Fingerprint` to produce the same output
    consistently across all platforms.

    This layer uses [FarmHash64](https://github.com/google/farmhash) by default,
    which provides a consistent hashed output across different platforms and is
    stable across invocations, regardless of device and context, by mixing the
    input bits thoroughly.

    If you want to obfuscate the hashed output, you can also pass a random
    `salt` argument in the constructor. In that case, the layer will use the
    [SipHash64](https://github.com/google/highwayhash) hash function, with
    the `salt` value serving as additional input to the hash function.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    **Example (FarmHash64)**

    >>> layer = tf.keras.layers.Hashing(num_bins=3)
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    <tf.Tensor: shape=(5, 1), dtype=int64, numpy=
      array([[1],
             [0],
             [1],
             [1],
             [2]])>

    **Example (FarmHash64) with a mask value**

    >>> layer = tf.keras.layers.Hashing(num_bins=3, mask_value='')
    >>> inp = [['A'], ['B'], [''], ['C'], ['D']]
    >>> layer(inp)
    <tf.Tensor: shape=(5, 1), dtype=int64, numpy=
      array([[1],
             [1],
             [0],
             [2],
             [2]])>

    **Example (SipHash64)**

    >>> layer = tf.keras.layers.Hashing(num_bins=3, salt=[133, 137])
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    <tf.Tensor: shape=(5, 1), dtype=int64, numpy=
      array([[1],
             [2],
             [1],
             [0],
             [2]])>

    **Example (Siphash64 with a single integer, same as `salt=[133, 133]`)**

    >>> layer = tf.keras.layers.Hashing(num_bins=3, salt=133)
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    <tf.Tensor: shape=(5, 1), dtype=int64, numpy=
      array([[0],
             [0],
             [2],
             [1],
             [0]])>

    Args:
      num_bins: Number of hash bins. Note that this includes the `mask_value`
        bin, so the effective number of bins is `(num_bins - 1)` if `mask_value`
        is set.
      mask_value: A value that represents masked inputs, which are mapped to
        index 0. Defaults to None, meaning no mask term will be added and the
        hashing will start at index 0.
      salt: A single unsigned integer or None.
        If passed, the hash function used will be SipHash64, with these values
        used as an additional input (known as a "salt" in cryptography).
        These should be non-zero. Defaults to `None` (in that
        case, the FarmHash64 hash function is used). It also supports
        tuple/list of 2 unsigned integer numbers, see reference paper for
        details.
      output_mode: Specification for the output of the layer. Defaults to
        `"int"`.  Values can be `"int"`, `"one_hot"`, `"multi_hot"`, or
        `"count"` configuring the layer as follows:
          - `"int"`: Return the integer bin indices directly.
          - `"one_hot"`: Encodes each individual element in the input into an
            array the same size as `num_bins`, containing a 1 at the input's bin
            index. If the last dimension is size 1, will encode on that
            dimension.  If the last dimension is not size 1, will append a new
            dimension for the encoded output.
          - `"multi_hot"`: Encodes each sample in the input into a single array
            the same size as `num_bins`, containing a 1 for each bin index
            index present in the sample. Treats the last dimension as the sample
            dimension, if input shape is `(..., sample_length)`, output shape
            will be `(..., num_tokens)`.
          - `"count"`: As `"multi_hot"`, but the int array contains a count of
            the number of times the bin index appeared in the sample.
      sparse: Boolean. Only applicable to `"one_hot"`, `"multi_hot"`,
        and `"count"` output modes. If True, returns a `SparseTensor` instead of
        a dense `Tensor`. Defaults to False.
      **kwargs: Keyword arguments to construct a layer.

    Input shape:
      A single or list of string, int32 or int64 `Tensor`,
      `SparseTensor` or `RaggedTensor` of shape `(batch_size, ...,)`

    Output shape:
      An int64 `Tensor`, `SparseTensor` or `RaggedTensor` of shape
      `(batch_size, ...)`. If any input is `RaggedTensor` then output is
      `RaggedTensor`, otherwise if any input is `SparseTensor` then output is
      `SparseTensor`, otherwise the output is `Tensor`.

    Reference:
      - [SipHash with salt](https://www.131002.net/siphash/siphash.pdf)

    NintFc                    s  |d u s|dkr t d| dd|vs4|d d u rP|tkrBtjnt |d< n"|dkrrt|d jsrtj|d< t j	f i | t
jdd |tkrt| jjs|d }t d| tj|ttttf| jjd	d
 |r|tkrt d| d| || _|| _|d urdnd| _|| _|| _d | _|d urt|ttfrft|dkrf|| _n(t|t r~||g| _nt d| dd S )Nr   zYThe `num_bins` for `Hashing` cannot be `None` or non-positive values. Received: num_bins=.dtyper	   r   TzMWhen `output_mode="int"`, `dtype` should be an integer type. Received: dtype=output_mode)allowable_strings
layer_namearg_namezi`sparse` may only be true if `output_mode` is `"one_hot"`, `"multi_hot"`, or `"count"`. Received: sparse=z and output_mode=F   znThe `salt` argument for `Hashing` can only be a tuple of size 2 integers, or a single integer. Received: salt=)!
ValueErrorINTtfint64r   floatxas_dtype
is_integersuper__init__r   keras_kpl_gaugeget_cellsetcompute_dtyper   validate_string_argONE_HOT	MULTI_HOTCOUNT	__class____name__num_bins
mask_valuestrong_hashr   sparsesalt
isinstancetuplelistlenr	   )selfr$   r%   r(   r   r'   kwargsinput_dtyper"    ^/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/layers/preprocessing/hashing.pyr      sp    	


zHashing.__init__c                 C   sZ   t |}t|tjr4tj|j| |j|jd}n
| |}t j	|| j
| j| j| jdS )N)indicesvaluesdense_shape)r   depthr'   r   )utilsensure_tensorr)   r   SparseTensorr3   _hash_values_to_binsr4   r5   encode_categorical_inputsr   r$   r'   r   )r-   inputsr3   r1   r1   r2   call   s    


zHashing.callc                 C   s   | j }d}| jdur2|dkr2|d8 }t|| j}|jjrDt|}| jrbtjj	||d| j
d}ntjj||dd}|durt|t|}t|t||}|S )z6Converts a non-sparse tensor of values to bin indices.N   hash)namekey)r@   )r$   r%   r   equalr   r   	as_stringr&   stringsto_hash_bucket_strongr(   to_hash_bucket_fastadd	ones_likewhere
zeros_like)r-   r4   Z	hash_binsmaskr1   r1   r2   r:      s$    

zHashing._hash_values_to_binsc                 C   s   |S )Nr1   )r-   input_shaper1   r1   r2   compute_output_shape  s    zHashing.compute_output_shapec                 C   s<   |  |j}t|tjr(tj|| jdS tj|| jdS d S )N)shaper   )rM   rN   r)   r   SparseTensorSpecr   
TensorSpec)r-   
input_specoutput_shaper1   r1   r2   compute_output_signature  s    z Hashing.compute_output_signaturec                    s.   t   }|| j| j| j| j| jd |S )N)r$   r(   r%   r   r'   )r   
get_configupdater$   r(   r%   r   r'   )r-   configr0   r1   r2   rT     s    
	zHashing.get_config)NNr	   F)r#   
__module____qualname____doc__r   r=   r:   rM   rS   rT   __classcell__r1   r1   r0   r2   r   #   s   y    K	r   )rY   tensorflow.compat.v2compatv2r   kerasr   keras.enginer   r   Zkeras.layers.preprocessingr   r7   keras.utilsr    tensorflow.python.util.tf_exportr   r   r    r   r!   Layerr   r1   r1   r1   r2   <module>   s   