o
    &jN                     @   s   d dl Zd dlmZ d dlmZ d/ddZd/ddZd0d
dZdd Z	d1ddZ
dd Zdd Zd2ddZd3ddZdd Zd/ddZdd Zd d! Zd3d"d#Z	$	d4d%d&Zd'd( Zd3d)d*Z	$	d4d+d,Zd-d. ZdS )5    N)Image)Recordc              
   c   sF    |  D ]\}}t|}ttj|| |tj||ddgdV  qdS )a(  Package data to scalars

    Args:
        main_tag (string): Data identifier
        tag_scalar_dict (dict): A dict to provide multi-values with tags
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    )tagvalue)idr   	timestampZ	tag_valuevaluesN)itemsfloatr   ValueZTagValue)Zmain_tagZtag_scalar_dictstepwalltimeZsub_tagr    r   b/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/visualdl/component/base_component.pyscalars   s   r   c                 C   s"   t |}ttj|| ||dgdS )a  Package data to one scalar.
    Args:
        tag (string): Data identifier
        value (float): Value of scalar
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    )r   r   r   r   r   )r   r   r   )r   r   r   r   r   r   r   scalar,   s   r   meta_data_tag c                 C   &   t j|d}t t j|| ||dgdS )aP  Package data to one meta_data.

    Meta data is info for one record file, include `display_name` etc.

    Args:
        tag (string): Data identifier
        display_name (string): Replace
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    )display_name)r   r   r   	meta_datar   )r   ZMetaDatar   )r   r   r   r   metar   r   r   r   =   s   r   c                 C   s   z!ddl }|| |j} |d| \}}tt|d}W |S  t	yU   ddl
}t| }| }|j|dd | }W d   Y |S 1 sMw   Y  Y |S w )zConvert image ndarray to bytes.

    Args:
        np_array (np.ndarray): Array to converte.

    Returns:
        Binary bytes of np_array.
    r   Nz.pngrawZpng)format)cv2ZcvtColorZCOLOR_BGR2RGBZimencoder   Z	fromarraynpuint8tobytesImportErrorioBytesIOsavegetvalue)Znp_arrayr   retbufZimg_binr    Zimfpr   r   r   imgarray2bytesQ   s"   	


r'      c           
   	   C   s.  t | tjs
J d| jd dkrt| | | gd} | jdkr&| jd dks/| jd dks/J | jd }| jd }| jd }t||}ttt	|| }tj
| jd || || f| jd}d}t|D ].}t|D ]'}	||krt n | | |d d || |d | |	| |	d | f< |d }qlqf|S )Nz*plugin error, should pass numpy array here         r      )dtype)
isinstancer   Zndarrayshapeconcatenatendimminintceilr   Zzerosr-   range)
IZncolsZnimgHWZnrowsZcanvasiyxr   r   r   	make_gridi   s.   *



$6
r<   c                    s  t t t  ksJ d t | jt  ks#J d| j    t  dkrF fdddD }| |}t|}|ddd	S t  d
krl fdddD }| |}|jd dkrjt|||gd}|S t  dkr fdddD }| |} t	| | | gd} | S dS )zConvert `NCHW`, `HWC`, `HW` to `HWC`

    Args:
        tensor (np.ndarray): Value of image
        input_format (string): Format of image

    Return:
        Image of format `HWC`.
    zLYou can not use the same dimension shordhand twice.         input_format: {}z_size of input tensor and input format are different.         tensor shape: {}, input_format: {}r*   c                       g | ]}  |qS r   find.0cinput_formatr   r   
<listcomp>       z"convert_to_HWC.<locals>.<listcomp>ZNCHWr)   r,   r   r+   c                    r=   r   r>   r@   rC   r   r   rE      rF   HWCc                    r=   r   r>   r@   rC   r   r   rE      rF   ZHWN)
lensetr   r/   upperZ	transposer<   r   r0   stack)ZtensorrD   indexZtensor_NCHWZ
tensor_CHWZ
tensor_HWCr   rC   r   convert_to_HWC   s8   




rM   c                 C   s,   |   dkr|  dkr| d9 } | tjS )zRenormalise ndarray matrix.

    Args:
        image_array(np.ndarray): Value of image

    Return:
        Matrix after renormalising.
    r)   r      )maxr2   astyper   r   )image_arrayr   r   r   denormalization   s   	rR   rG   c                 C   s@   t |}t||}t|}tj|d}ttj|| ||dgdS )a:  Package data to one image.

    Args:
        tag (string): Data identifier
        image_array (np.ndarray): Value of image
        step (int): Step of image
        walltime (int): Wall time of image
        dataformats (string): Format of image

    Return:
        Package with format of record_pb2.Record
    )Zencoded_image_string)r   r   r   imager   )rR   rM   r'   r   r   r   )r   rQ   r   r   ZdataformatsZimage_bytesrS   r   r   r   rS      s   
rS   c           
         s   t  }|r|j| t|d tr.g }tt|d D ] | fdd|D  q|}t	||D ]\}}	t|ts?|g}|j
t j||	d q3t t j|| ||dgdS )av  Package data to one embedding.

    Args:
        tag (string): Data identifier
        labels (list): A list of labels.
        hot_vectors (np.array or list): A matrix which each row is
            feature of labels.
        step (int): Step of embeddings.
        walltime (int): Wall time of embeddings.

    Return:
        Package with format of record_pb2.Record
    r   c                    s   g | ]}|  qS r   r   )rA   labelrL   r   r   rE      s    zembedding.<locals>.<listcomp>)rT   Zvectors)r   r   r   
embeddingsr   )r   Z
EmbeddingsZ
label_metaextendr.   listr5   rH   appendziprV   Z	Embeddingr   )
r   labelsZhot_vectorsr   Zlabels_metar   rV   temprT   Z
hot_vectorr   rU   r   	embedding   s&   
r]   c                 C   s  |  }t| dkrtd |dd}|jdksJ ddd |D }ddl}ddl}ddl}|	 }|
|d	}	|	d |	d
 |	| d}
|
|jddt|  g|R  7 }
|	|
 |	  | }|  tj|dt||dd}ttj|| ||dgdS )aU  Package data to one audio.

    Args:
        tag (string): Data identifier
        audio_array (np.ndarray or list): audio represented by a np.array
        sample_rate (int): Sample rate of audio
        step (int): Step of audio
        walltime (int): Wall time of audio

    Return:
        Package with format of record_pb2.Record
    r)   z4warning: audio amplitude out of range, auto clipped.z%input tensor should be 1 dimensional.c                 S   s   g | ]}t d | qS )g    @)r3   )rA   r;   r   r   r   rE     s    zaudio.<locals>.<listcomp>r   Nwbr,       <hz	audio/wav)sample_rateZnum_channelsZlength_framesZencoded_audio_stringcontent_type)r   r   r   audior   )ZsqueezeabsrO   printZclipr1   r    wavestructr!   openZsetnchannelsZsetsampwidthZsetframeratepackrH   Zwriteframescloser#   r   ZAudior   )r   Zaudio_arrayrc   r   r   r    rh   ri   ZfioZwave_writerZ	audio_encZaudio_stringZ
audio_datar   r   r   re      s<   


"
re   c                 C   r   )a  Package data to one image.
    Args:
        tag (string): Data identifier
        text_string (string): Value of text
        step (int): Step of text
        walltime (int): Wall time of text
    Return:
        Package with format of record_pb2.Record
    )Zencoded_text_string)r   r   r   textr   )r   Textr   )r   Ztext_stringr   r   _textr   r   r   rm     s   
rm   c                 C   s(   t j||d}t t j|| ||dgdS )a\  Package data to one histogram.

    Args:
        tag (string): Data identifier
        hist (np.ndarray or list): The values of the histogram
        bin_edges (np.ndarray or list): The bin edges
        step (int): Step of histogram
        walltime (int): Wall time of histogram

    Return:
        Package with format of record_pb2.Record
    )hist	bin_edges)r   r   r   	histogramr   )r   Z	Histogramr   )r   rp   rq   r   r   rr   r   r   r   rr   -  s   rr   c           
      C   s   t  }| |_| D ]J\}}|du rqt j }||_t|tr+||_|j	| qt|t
r:||_|j	| qt|trI||_|j	| qtd|tt|f  q|D ]}t j }	||	_d|	_|j	|	 qXt t jdd||dgdS )a  Package data to one histogram.

    Args:
        name (str): Name of hparam.
        hparam_dict (dictionary): Each key-value pair in the dictionary is the
              name of the hyper parameter and it's corresponding value. The type of the value
              can be one of `bool`, `string`, `float`, `int`, or `None`.
        metric_list (list): Name of all metrics.
        walltime (int): Wall time of hparam.

    Return:
        Package with format of record_pb2.Record
    Nz1The value of %s must be int, float or str, not %sr   r)   hparam)r   r   r   rs   r   )r   ZHParamnamer
   Z
HparamInfor.   r3   Z	int_valueZhparamInfosrY   r   float_valuestrZstring_valuerg   typeZmetricInfosr   )
rt   Zhparam_dictZmetric_listr   ZhmkvZ
hparamInfoZmetricZ
metricInfor   r   r   rs   A  s6   




rs   c                 C   sn  t | tr
t| } t |trt|}d}|du rd}tt||d  }| tj}d|d f}tj||||| d\}}	tj|||d| | d\}
}	t	|ddd ddd }t	|
ddd ddd }|d | }|d | }|t
|||  }|t
|||  }|t |t |t |t |t |t d}|S )	a   Compute precision-recall curve data by labels and predictions.

    Args:
        labels (np.ndarray or list): Binary labels for each element.
        predictions (np.ndarray or list): The probability that an element be
            classified as true.
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    Hz>N      ?r)   r   Zbinsr5   weightsr^   )tpr&   tnfn	precisionrecallr.   rX   r   arrayZint32floorrP   r   rr   Zcumsummaximumr3   tolist)r[   predictionsnum_thresholdsr}   _MINIMUM_COUNTbucket_indicesfloat_labelshistogram_range
tp_buckets_
fp_bucketsr~   r&   r   r   r   r   datar   r   r   compute_curven  sH   







r      c                 C   J   t |d}t||||}t| |d |d |d |d |d |d ||d	S )	a$  Package data to one pr_curve.

    Args:
        tag (string): Data identifier
        labels (np.ndarray or list): Binary labels for each element.
        predictions (np.ndarray or list): The probability that an element be
            classified as true.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.

    Return:
        Package with format of record_pb2.Record
    r   r~   r&   r   r   r   r   )	r   r~   r&   r   r   r   r   r   r   )r2   r   pr_curve_raw)r   r[   r   r   r   r   r}   Zprcurve_mapr   r   r   pr_curve  s   
r   c	           
      C   2   	 t j||||||d}	t t j|| ||	dgdS )a  Package raw data to one pr_curve.

    Args:
        tag (string): Data identifier
        tp (list): True Positive.
        fp (list): False Positive.
        tn (list): True Negative.
        fn (list): False Negative.
        precision (list): The fraction of retrieved documents that are relevant
            to the query:
        recall (list): The fraction of the relevant documents that are
            successfully retrieved.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.

    Return:
        Package with format of record_pb2.Record
    )TPFPTNFNr   r   )r   r   r   r   r   )r   ZPRCurver   )
r   r~   r&   r   r   r   r   r   r   Zprcurver   r   r   r     s   r   c                 C   sn  t | tr
t| } t |trt|}d}|du rd}tt||d  }| tj}d|d f}tj||||| d\}}	tj|||d| | d\}
}	t	|ddd ddd }t	|
ddd ddd }|d | }|d | }|t
|||  }|t
|||  }|t |t |t |t |t |t d}|S )	a   Compute ROC curve data by labels and predictions.
    Args:
        labels (numpy.ndarray or list): Binary labels for each element.
        predictions (numpy.ndarray or list): The probability that an element be
            classified as true.
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    rz   Nr{   r)   r   r|   r^   )r~   r&   r   r   tprfprr   )r[   r   r   r}   r   r   r   r   r   r   r   r~   r&   r   r   r   r   r   r   r   r   compute_roc_curve  sH   
	





r   c                 C   r   )	a)  Package data to one roc_curve.
    Args:
        tag (string): Data identifier
        labels (numpy.ndarray or list): Binary labels for each element.
        predictions (numpy.ndarray or list): The probability that an element be
            classified as true.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    Return:
        Package with format of record_pb2.Record
    r   r~   r&   r   r   r   r   )	r   r~   r&   r   r   r   r   r   r   )r2   r   roc_curve_raw)r   r[   r   r   r   r   r}   Zroc_curve_mapr   r   r   	roc_curve"  s   
r   c	           
      C   r   )aR  Package raw data to one roc_curve.
    Args:
        tag (string): Data identifier
        tp (list): True Positive.
        fp (list): False Positive.
        tn (list): True Negative.
        fn (list): False Negative.
        tpr (list): true positive rate:
        fpr (list): false positive rate.
        step (int): Step of roc_curve
        walltime (int): Wall time of roc_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    Return:
        Package with format of record_pb2.Record
    )r   r   r   r   r   r   )r   r   r   r   r   )r   Z	ROC_Curver   )
r   r~   r&   r   r   r   r   r   r   r   r   r   r   r   F  s   r   )N)r   r   r   N)r(   )NrG   )NN)r   N)numpyr   ZPILr   Zvisualdl.proto.record_pb2r   r   r   r   r'   r<   rM   rR   rS   r]   re   rm   rr   rs   r   r   r   r   r   r   r   r   r   r   <module>   s4   



'

$
/
-8
%
*7
$