o
    wi=                     @   s   d dl Z d dlZd dlZd dlmZ d dlZd dlmZ ddl	m
Z
 zd dlZdad dlmZ W n ey;   daY nw eeZG d	d
 d
ZdS )    N)BytesIO)MessageToJson   )
_clean_tagT)ImageFc                   @   s0  e Zd ZddifddZdd Zedd Ze			d,d
dZed-ddZed.ddZe					d/ddZ	ed.ddZ
e				d0ddZed1ddZed2ddZed1ddZe			d3ddZe				d4dd Ze					!				d5d"d#Zed$d% Zed1d&d'Zed1d(d)Ze		d1d*d+Zd	S )6CometLoggerdisabledTc                 C   sF   d | _ || _|d du rd| _ d S |d du rtdu r!tdd S d S )Nr   TFzRComet and/or Python Image Library not installed. Run 'pip install comet-ml pillow')_logging_comet_configcomet_installed	Exception)selfcomet_config r   U/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/tensorboardX/comet_utils.py__init__   s   
zCometLogger.__init__c                    s   t   fdd}|S )Nc               
      s   | d }|j d u rPtrPd|_ z*d|jvrt  t d ur#td tjdi |j|_	d|_ |j	
dd W n tyO } zt| W Y d }~nd }~ww |j du r\ | i |S d S )	Nr   Fapi_keyzYou have already created a comet                                         experiment manually, which might                                         cause clashesTzCreated fromtensorboardXr   )r	   r   r
   comet_mlinitget_global_experimentloggerwarning
Experiment_experiment	log_otherr   )argskwargsr   emethodr   r   wrapper   s$   


z+CometLogger._requiresComet.<locals>.wrapper)	functoolswraps)r    r!   r   r   r   _requiresComet   s   zCometLogger._requiresCometc                 C   s   | j   dtj_dS )zEnds an experiment.N)r   endr   config
experiment)r   r   r   r   r%   6   s   
zCometLogger.endNc                 C   s,   |dkrt |n|}| j||||| dS )a'  Logs a general metric (i.e accuracy, f1)..

        Args:
            tag: String - Data identifier
            display_name: The title of the plot. If empty string is passed,
              `tag` will be used.
            value: Float/Integer/Boolean/String
            step: Optional. Used as the X axis when plotting on comet.ml
            epoch: Optional. Used as the X axis when plotting on comet.ml
            include_context: Optional. If set to True (the default),
                the current context will be logged along the metric.
         N)r   r   
log_metric)r   tagdisplay_namevaluestepepochinclude_contextnamer   r   r   r)   <   s   zCometLogger.log_metricc                 C   s   | j |||| dS )a3  Logs a key,value dictionary of metrics.

        Args:
            dic: key,value dictionary of metrics
            prefix: prefix added to metric name
            step: Optional. Used as the X axis when plotting on comet.ml
            epoch: Optional. Used as the X axis when plotting on comet.ml
        N)r   log_metrics)r   dicprefixr-   r.   r   r   r   r1   O   s   
zCometLogger.log_metricsc                 C      | j ||| dS )a  Logs a dictionary (or dictionary-like object) of multiple parameters.

        Args:
            parameters: key,value dictionary of parameters
            prefix: prefix added to metric name
            step: Optional. Used as the X axis when plotting on comet.ml
        N)r   log_parameters)r   
parametersr3   r-   r   r   r   r5   [   s   	zCometLogger.log_parametersFc              	   C   s   | j ||||||| dS )a:  Logs the audio Asset determined by audio data.

        Args:
        audio_data: String or a numpy array - either the file path
            of the file you want to log, or a numpy array given to
            scipy.io.wavfile.write for wav conversion.
        sample_rate: Integer - Optional. The sampling rate given to
            scipy.io.wavfile.write for creating the wav file.
        file_name: String - Optional. A custom file name to be displayed.
            If not provided, the filename from the audio_data argument
            will be used.
        metadata: Some additional data to attach to the the audio asset.
            Must be a JSON-encodable dict.
        overwrite: if True will overwrite all existing assets with the same name.
        copy_to_tmp: If audio_data is a numpy array, then this flag
            determines if the WAV file is first copied to a temporary
            file before upload. If copy_to_tmp is False, then it is sent
            directly to the cloud.
        step: Optional. Used to associate the audio asset to a specific step.
        N)r   	log_audio)r   
audio_datasample_rate	file_namemetadata	overwritecopy_to_tmpr-   r   r   r   r7   f   s   zCometLogger.log_audioc                 C   r4   )a3  Logs the text. These strings appear on the Text Tab in the Comet UI.

        Args:
        text: string to be stored
        step: Optional. Used to associate the asset to a specific step.
        metadata: Some additional data to attach to the the text. Must
            be a JSON-encodable dict.
        N)r   log_text)r   textr-   r;   r   r   r   r>      s   
zCometLogger.log_textc                 K   s    | j j|||||fi | dS )a  Logs a histogram of values for a 3D chart as an asset for
           this experiment. Calling this method multiple times with the
           same name and incremented steps will add additional histograms
           to the 3D chart on Comet.ml.

        Args:
        values: a list, tuple, array (any shape) to summarize, or a
            Histogram object
        name: str (optional), name of summary
        step: Optional. Used as the Z axis when plotting on Comet.ml.
        epoch: Optional. Used as the Z axis when plotting on Comet.ml.
        metadata: Optional: Used for items like prefix for histogram name.
        kwargs: Optional. Additional keyword arguments for histogram.
        N)r   log_histogram_3d)r   valuesr0   r-   r.   r;   r   r   r   r   log_histogram   s
   
zCometLogger.log_histogramc                 C   s0   |j d j}t|}||d< | j|||d dS )a  Log Raw Histogram Data to Comet as an Asset.

        Args:
            tag: Name given to the logged asset
            summary: TensorboardX Summary protocol buffer with histogram data
            step: The Global Step for this experiment run. Defaults to None.
        r   r0   )datar0   r-   N)r,   histor   log_asset_data)r   r*   summaryr-   histogram_protohistogram_raw_datar   r   r   log_histogram_raw   s   
zCometLogger.log_histogram_rawc                 C   s    | j || | || dS )a  Log timeseries data.

        Args:
        name: (str) name of data
        x: array of x-axis values
        y: array of y-axis values
        overwrite: (optional, bool) if True, overwrite previous log
        step: (optional, int) the step value
        N)r   	log_curvetolist)r   r0   xyr<   r-   r   r   r   rJ      s    zCometLogger.log_curvec                 C   s0   t |}t|}t|}| jj|||d dS )a  Logs the image. Images are displayed on the Graphics tab on Comet.ml.

        Args:
        encoded_image_string: Required. An encoded image string
        tag: String - Data identifier
        step: Optional. Used to associate the image asset to a specific step.
        r-   N)r   r   openr   r   	log_image)r   encoded_image_stringr*   r-   buff	image_pilr0   r   r   r   log_image_encoded   s   	
zCometLogger.log_image_encodedc                 C      | j |||||| dS )a  Logs the Asset determined by file_data.

        Args:
        file_data: String or File-like - either the file path of the
            file you want to log, or a file-like asset.
        file_name: String - Optional. A custom file name to be displayed.
            If not provided the filename from the file_data argument will be used.
        overwrite: if True will overwrite all existing assets with
            the same name.
        copy_to_tmp: If file_data is a file-like object, then this flag
            determines if the file is first copied to a temporary file
            before upload. If copy_to_tmp is False, then it is sent
            directly to the cloud.
        step: Optional. Used to associate the asset to a specific step.
        N)r   	log_asset)r   	file_datar:   r<   r=   r-   r;   r   r   r   rV      s   zCometLogger.log_assetc                 C   rU   )a  Logs the data given (str, binary, or JSON).

        Args:
        data: data to be saved as asset
        name: String, optional. A custom file name to be displayed If
            not provided the filename from the temporary saved file
            will be used.
        overwrite: Boolean, optional. Default False. If True will
            overwrite all existing assets with the same name.
        step: Optional. Used to associate the asset to a specific step.
        epoch: Optional. Used to associate the asset to a specific epoch.
        metadata: Optional. Some additional data to attach to the
            asset data. Must be a JSON-encodable dict.
        N)r   rE   )r   rC   r0   r<   r-   r;   r.   r   r   r   rE      s   zCometLogger.log_asset_dataComet Embeddingc
                 C   s   d}
|du rdS |dur'|    }|jdd }
|
d dkr'|
dd }
t|tkr3t|}n|    }| j	||||
||||||	
 dS )a  Log a multi-dimensional dataset and metadata for viewing
           with Comet's Embedding Projector (experimental).

        Args:
        vectors: the tensors to visualize in 3D
        labels: labels for each tensor
        image_data: (optional) list of arrays or Images
        image_preprocess_function: (optional) if image_data is an array,
            apply this function to each element first
        image_transparent_color: a (red, green, blue) tuple
        image_background_color_function: a function that takes an
            index, and returns a (red, green, blue) color tuple
        title: (optional) name of tensor
        template_filename: (optional) name of template JSON file
        Nr   r   )
cpudetachnumpyshapetypelistnparrayr   log_embedding)r   vectorslabels
image_dataimage_preprocess_functionimage_transparent_colorimage_background_color_functiontitletemplate_filenamegroup
image_sizer   r   r   ra      s$   zCometLogger.log_embeddingc           	      C   sf   i }||d< |  |d< |  |d< |  |d< ||d< ||d< d|d< t|}| j|||d	 d
S )a  Logs a mesh as an asset

        Args:
        tag: Data identifier
        vertices: List of the 3D coordinates of vertices.
        colors: Colors for each vertex
        faces: Indices of vertices within each triangle.
        config_dict: Dictionary with ThreeJS classes names and configuration.
        step: step value to record
        walltime: Optional override default walltime (time.time())
            seconds after epoch of event
        r*   verticescolorsfacesconfig_dictwalltimemesh
asset_typerN   N)rK   jsondumpsrE   )	r   r*   rl   rm   rn   ro   r-   rp   	mesh_jsonr   r   r   log_mesh  s   
zCometLogger.log_meshc                 K   s    |}||d< | j |||d dS )zLogs a histogram as an asset.

        Args:
        tag: Data identifier
        asset_type: List of the 3D coordinates of vertices.
        step: step value to record
        rr   rN   N)rE   )r   r*   rr   r-   r   	file_jsonr   r   r   log_raw_figure8  s   	zCometLogger.log_raw_figurec              	      s   |j d j}dd |jjD }tj|jtjd|} fddt	 D }t
dd t||jd \}	}
}}}}|	|
||||||d}| j|||d	 d
S )Logs a Precision-Recall Curve Data as an asset.

        Args:
        tag: An identifier for the PR curve
        summary: TensorboardX Summary protocol buffer.
        step: step value to record
        r   c                 S   s   g | ]}|j qS r   )size).0dr   r   r   
<listcomp>O  s    z+CometLogger.log_pr_data.<locals>.<listcomp>)dtypec                       g | ]}d   | qS g      ?r   r{   inum_thresholdsr   r   r}   R      c                 S      |    S NflattenrK   rL   r   r   r   <lambda>S      z)CometLogger.log_pr_data.<locals>.<lambda>)TPFPTNFN	precisionrecall
thresholdsr0   r0   r-   N)r,   tensortensor_shapedimr_   fromiter	float_valfloat32reshaperangemapvsplitr\   rE   )r   r*   rF   r   r-   tensor_protor\   rA   r   tpfptnfnr   r   pr_datar   r   r   log_pr_dataE  s   	(zCometLogger.log_pr_datac              
      sh    fddt  D }tdd ||||||g\}}}}}}||||||||	|d	}| j|||
d dS )ry   c                    r   r   r   r   r   r   r   r}   n  r   z/CometLogger.log_pr_raw_data.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   r   o  r   z-CometLogger.log_pr_raw_data.<locals>.<lambda>)	r   r   r   r   r   r   r   weightsr0   r   N)r   r   rE   )r   r*   true_positive_countsfalse_positive_countstrue_negative_countsfalse_negative_countsr   r   r   r   r-   r   r   r   r   r   r   r   r   r   log_pr_raw_datab  s(   	zCometLogger.log_pr_raw_data)NNT)NNN)NN)NNNFTN)NNNNr   )FN)NFTNN)NFNNN)NNNNrX   NN)__name__
__module____qualname__r   r$   r%   r)   r1   r5   r7   r>   rB   rI   rJ   rT   rV   rE   ra   rv   rx   r   r   r   r   r   r   r      sl    	

'
r   )r"   rs   loggingior   r[   r_   google.protobuf.json_formatr   rF   r   r   r   PILr   ImportError	getLoggerr   r   r   r   r   r   r   <module>   s     
