o
    wic                     @   sz  d dl Z d dlZd dlZd dl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mZmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZ e eZedZ dd Z!d?ddZ"d@ddZ#dAddZ$dd Z%dBddZ&dBddZ'dCdd Z(dDd!d"Z)dBd#d$Z*dEd%d&Z+dFd)d*Z,d+d, Z-dGd.d/Z.d0d1 Z/d2d3 Z0dHd5d6Z1dHd7d8Z2d@d9d:Z3d;d< Z4dBd=d>Z5dS )I    N   )
layout_pb2)MeshPluginData)PrCurvePluginData)TextPluginData)HistogramProtoSummarySummaryMetadata)TensorProto)TensorShapeProto)_prepare_videoconvert_to_HWCconvert_to_NTCHW)make_npz	[^-/\w\.]c                 C   sF   | d ur!t d| }|d}|| kr!td|  d| d |} | S )N_/zSummary name z is illegal; using z	 instead.)_INVALID_TAG_CHARACTERSsublstriploggerinfo)namenew_name r   Q/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/tensorboardX/summary.py
_clean_tag   s   
r   black   c	                 C   s   ddl m}	m}
 |
 }|	| }||||f\}}}}|j||f||f||f||f||fg||d |ru|}||\}}}}|| || }}td| }|j	||| d|  f|| |fg|d |j
|| || | f|||d | S )Nr   )	ImageDraw	ImageFont)widthfillg?r   )r!   )r!   font)PILr   r   load_defaultDrawlinegetbboxnpceil	rectangletext)imagexminyminxmaxymaxdisplay_strcolor
color_text	thicknessr   r   r"   drawleftrighttopbottomtext_bottomltrb
text_widthtext_heightmarginr   r   r   _draw_single_box*   s2   

rB   c                    sH  ddl m}m}m}m mm} ddlm}m	}m
} d}	d}
d}d}d}g }| }|  D ]\}}|d u r6q-t|trN||j| _||||dd	 q-t|trf||j| _||||d
d	 q-t|ttfrt|d }||j| _||||dd	 q-t|rt|dt||j| _||||dd	 q-||||dd	 q-|||
d}ttj|	| dd}ttj||dgd} fdd|D }|||d}|||
d}ttj|	| dd}ttj||dgd}||dd}|||
d}ttj|	| dd}ttj||dgd}|||fS )Nr   )DataType
Experiment
HParamInfo
MetricInfo
MetricNameStatus)HParamsPluginDataSessionEndInfoSessionStartInfohparamsz_hparams_/experimentz_hparams_/session_start_infoz_hparams_/session_end_infoDATA_TYPE_STRING)r   typeDATA_TYPE_BOOLDATA_TYPE_FLOAT64__name__DATA_TYPE_UNSET)session_start_infoversionplugin_namecontentplugin_data)tagmetadatavaluec                    s   g | ]
} |d dqS )rZ   )r   r   ).0krF   rG   r   r   
<listcomp>   s    zhparams.<locals>.<listcomp>)hparam_infosmetric_infos)
experimentrT   STATUS_SUCCESS)status)session_end_inforT   )tensorboardX.proto.api_pb2rC   rD   rE   rF   rG   rH   %tensorboardX.proto.plugin_hparams_pb2rI   rJ   rK   items
isinstancestrrL   string_valueappendValuebool
bool_valueintfloatr   number_valuecallablegetattrr	   
PluginDataSerializeToStringr   )hparam_dictmetric_dictrC   rD   rE   rH   rI   rJ   rK   PLUGIN_NAMEPLUGIN_DATA_VERSIONEXPERIMENT_TAGSESSION_START_INFO_TAGSESSION_END_INFO_TAGhpsssir`   vrW   smdmtsexpseir   ra   r   rL   B   sb    





rL    c                 C   s|   t | } t|}| jdksJ dt| }|dkr,|dkr,ttj| |dgdS t||d}ttj| ||dgdS )a  Outputs a `Summary` protocol buffer containing a single scalar value.
    The generated Summary has a Tensor.proto containing the input Tensor.
    Args:
      name: A name for the generated node. Will also serve as the series name in
        TensorBoard.
      tensor: A real numeric Tensor containing a single value.
      display_name: The title of the plot. If empty string is passed, `name` will be used.
      summary_description: The comprehensive text that will showed by clicking the information icon on TensorBoard.
    Returns:
      A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf.
    Raises:
      ValueError: If tensor has the wrong shape or type.
    r   zscalar should be 0Dr   )rZ   simple_valuer\   )display_namesummary_description)rZ   r   r[   )r   r   squeezendimrt   r   rp   r	   )r   scalarr   r   r[   r   r   r   r      s   r   c           	   	   C   s,   t |||||||d}ttj| |dgdS )a  Outputs a `Summary` protocol buffer with a histogram.
    The generated
    [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
    has one summary value containing a histogram for `values`.
    Args:
      name: A name for the generated node. Will also serve as a series name in
        TensorBoard.
      min: A float or int min value
      max: A float or int max value
      num: Int number of values
      sum: Float or int sum of all values
      sum_squares: Float or int sum of squares for all values
      bucket_limits: A numeric `Tensor` with upper value per bucket
      bucket_counts: A numeric `Tensor` with number of values per bucket
    Returns:
      A scalar `Tensor` of type `string`. The serialized `Summary` protocol
      buffer.
    minmaxnumsumsum_squaresbucket_limitbucketrZ   histor\   )r   r   rp   )	r   r   r   r   r   r   bucket_limitsbucket_countshistr   r   r   histogram_raw   s   r   c                 C   s8   t | } t|}t|t||}ttj| |dgdS )ad  Outputs a `Summary` protocol buffer with a histogram.
    The generated
    [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
    has one summary value containing a histogram for `values`.
    This op reports an `InvalidArgument` error if any value is not finite.
    Args:
      name: A name for the generated node. Will also serve as a series name in
        TensorBoard.
      values: A real numeric `Tensor`. Any shape. Values to use to
        build the histogram.
    Returns:
      A scalar `Tensor` of type `string`. The serialized `Summary` protocol
      buffer.
    r   r\   )r   r   make_histogramastypert   r   rp   )r   valuesbinsmax_binsr   r   r   r   	histogram   s   r   c              	   C   s  | j dkr	td| d} tj| |d\}}t|}|dure||kre|| }|| }|dkr=tj|d|| ggddd}|d|jdd}t|j d	 f|j	}|dd| |dd< |d |d< |}t
t|d}	tj|	d|	d d	 gd
d\}
}t|
}
t|d	 }~	|
dkr||
d	 | ntdg|d| g}||
|d	  }|j dks|j dkrtd| | }t|  |  t| |  || | dS )zDConvert values into a histogram proto using logic from histogram.cc.r   zThe input has no element.)r   Nconstant)	pad_widthmodeconstant_valuesaxisr   r7   )sidez1The histogram is empty, please file a bug report.r   )size
ValueErrorreshaper(   r   lenpadr   emptydtypecumsumgreatersearchsortedrs   concatenatedotr   r   r   tolist)r   r   r   countslimitsnum_binssubsamplingsubsampling_remainder
new_limits
cum_countsstartendsum_sqr   r   r   r      sF   

 0
r   CHWc                 C   sX   t | } t|}t||}|jtjkr|d tj}t||d}ttj	| |dgdS )a  Outputs a `Summary` protocol buffer with images.
    The summary has up to `max_images` summary values containing images. The
    images are built from `tensor` which must be 3-D with shape `[height, width,
    channels]` and where `channels` can be:
    *  1: `tensor` is interpreted as Grayscale.
    *  3: `tensor` is interpreted as RGB.
    *  4: `tensor` is interpreted as RGBA.

    Args:
      tag: A name for the generated node. Will also serve as a series name in
        TensorBoard.
      tensor: A 3-D `uint8` or `float32` `Tensor` of shape `[height, width,
        channels]` where `channels` is 1, 3, or 4.
        'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8).
        The image() function will scale the image values to [0, 255] by applying
        a scale factor of either 1 (uint8) or 255 (float32).
    Returns:
      A scalar `Tensor` of type `string`. The serialized `Summary` protocol
      buffer.
         o@)rescalerZ   r,   r\   )
r   r   r   r   r(   uint8r   
make_imager   rp   )rZ   tensorr   dataformatsr,   r   r   r   r,     s   
r,   c                 C   s\   t |}t||}t |}|jtjkr|d tj}t||||d}ttj| |dgdS )z0Outputs a `Summary` protocol buffer with images.r   )r   roislabelsr   r\   )	r   r   r   r(   r   r   r   r   rp   )rZ   tensor_imagetensor_boxesr   r   r   r,   r   r   r   image_boxes+  s   
r   c              
   C   sf   |j d }t|}|D ]%}t| ||df ||df ||df ||df |d u r)d n|| dd} q| S )Nr   r   r      Red)r1   r2   )shaperangerB   )
disp_imageboxesr   	num_boxeslist_gtir   r   r   
draw_boxes:  s   




r   c                 C   s   ddl }ddlm} ddl m} | j\}}}	t|| }
t|| }|| }|dur2t|||d}||j|dkrF|	||
f|j
j}n	|	||
f|j}ddl}| }|j|dd | }|  tj|||	|d	S )
z7Convert an numpy representation image to Image protobufr   N)parse)Image)r   z9.1.0PNG)formatheightr    
colorspaceencoded_image_string)r#   packaging.versionr   r   r   rs   	fromarrayr   __version__resize
ResamplingLANCZOSioBytesIOsavegetvaluecloser   )r   r   r   r   r#   r   r   r   r    channelscaled_heightscaled_widthr,   r   outputimage_stringr   r   r   r   I  s,   
r      NTCHWc                 C   s`   t | } t|}t||d}t|}|jtjkr |d tj}t||}t	t	j
| |dgdS )N)input_formatr   r   r\   )r   r   r   r   r   r(   r   r   
make_videor   rp   )rZ   r   fpsr   videor   r   r   r   d  s   
r   c                 C   s<  dd l }ddlm} ddlm} ddlm} z||d}W n |y-   td Y d S w zddlm	} W n, t
yb   zddlm	} W n t
y_ } ztd| W Y d }~Y d S d }~ww Y nw ||d	}	||d
krz|	|dk rztd | j\}
}}}|dkr||d
ks|	|dkrtj| ddd} |t| |d}|jdddd}|j}||dk rtd |j|dd n||dk r|j|dd d n|j|d d t|d}| }W d    n1 sw   Y  zt| W n ty   td Y nw W d    n	1 sw   Y  tj||||dS )Nr   )PackageNotFoundErrorrT   )Versionmoviepyzmoviepy is not installed.)ImageSequenceClipzgCan't create video. moviepy is installed, but can't import moviepy.video.io.ImageSequenceClip due to %rimageio2z2.29zYou are using moviepy >= 2.0.0 and imageio < 2.29.0. This combination is known to cause issues when writing videos. Please upgrade imageio to 2.29 or later, or use moviepy < 2.0.0.r   z2.27r   r   r   )r   z.gifF)suffixdeletez1.0.0z8Upgrade to moviepy >= 1.0.0 to supress the progress bar.)verbosez	2.0.0dev1)r   r   )r   rbz5The temporary file used by moviepy cannot be deleted.r   )tempfileimportlib.metadatar   rT   r   r   r   errorr   r   ImportError"moviepy.video.io.ImageSequenceClipr   r(   repeatlistNamedTemporaryFiler   warning	write_gifopenreadosremoveOSErrorr   r   )r   r   r  r   get_versionr   moviepy_versionr   eimageio_versionr<   hwcclipfpfilenameftensor_stringr   r   r   r   q  sn   


r   D  c           
      C   s   ddl }ddl}t|}t| dkrtd |dd}|jdkr*tj	|dd}|jdks3J d|j
\}}|dksD|dksDJ d	| }|j|||d
d | }W d   n1 s`w   Y  tj||||dd}	ttj| |	dgdS )z
    Args:
      tensor: A 2-D float Tensor of shape `[frames, channels]` where `channels` is 1 or 2.
        The values should between [-1, 1]. We also accepts 1-D tensor.
    r   Nr   z4warning: audio amplitude out of range, auto clipped.r   r   r   z%Input tensor should be 2 dimensional.z&The second dimension should be 1 or 2.wav)
samplerater   z	audio/wav)sample_ratenum_channelslength_framesencoded_audio_stringcontent_type)rZ   audior\   )r   	soundfiler   absr   printr  r   r(   expand_dimsr   r   writer   r   Audiorp   )
rZ   r   r   r   r&  r"  r!  fioaudio_stringr%  r   r   r   r%    s,   



r%  c                 C   s  g }|   D ]Y\}}g }|  D ]D\}}|d }|d dkrBt|dks&J tjtjj|d |d |d dgd}tj||d}	ntj|d	}
tj||
d
}	||	 q|tj||d qtj	|d} t
jdd}t
|d}td|  gt d}ttjd||dgdS )Nr   r   Marginr   r   )r]   lowerupper)series)titlerA   r^   )r2  	multiline)r2  chart)categorycustom_scalars)rV   rX   	DT_STRINGr   
string_valtensor_shapecustom_scalars__config__rZ   r   r[   r\   )rk   r   r   MarginChartContentSeriesChartMultilineChartContentro   CategoryLayoutr	   rx   r
   ry   r   r   rp   )layout
categoriesr`   r   charts
chart_namechart_meatadatatagsmgccr4  mlccrx   r   r   r   r   r   r6    s0   
r6  c                 C   sn   dd l }tjdtdd d}t|d}td|jddgttjd	d
gdd}t	t	j
| d ||dgdS )Nr   r+   r   rU   rX   r7  utf_8)encodingr   r   dimr8  z/text_summaryrZ   r[   r   r\   )jsonr	   rx   r   ry   r
   encoder   Dimr   rp   )rZ   r+   rQ  rx   r   r   r   r   r   r+     s   
r+      c	                 C   s   |dkrd}t ||||||f}	td|d }
tjd|
d}t|d}td|	d t	t	j
|	jd d	t	j
|	jd
 d	gdd}ttj| ||dgdS )NrT  r   rT   num_thresholds	pr_curvesrU   rX   DT_FLOATr   rM  r   rN  r   	float_valr:  rP  r\   )r(   stackr   ry   r	   rx   r
   r   r   r   rS  r   r   rp   )rZ   tpr  tnfn	precisionrecallrV  weightsdatapr_curve_plugin_datarx   r   r   r   r   r   pr_curve_raw  s&   
"rd  c           
      C   s   t |d}t||||d}td|d }tjd|d}t|d}td|d	 t	t	j
|jd d
t	j
|jd d
gdd}	ttj| ||	dgdS )NrT  )rV  ra  r   rU  rW  rU   rX   rX  r   rM  r   rN  rY  rP  r\   )r   compute_curver   ry   r	   rx   r
   r   r   r   rS  r   r   rp   )
rZ   r   predictionsrV  ra  rb  rc  rx   r   r   r   r   r   pr_curve  s(   

"rg  c                 C   s  d}|d u rd}t t ||d  }| t}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 ||||||fS )NgHz>g      ?r   r   )r   r   ra  r   )	r(   int32floorr   rt   r   r   maximumr[  )r   rf  rV  ra  _MINIMUM_COUNTbucket_indicesfloat_labelshistogram_range
tp_bucketsr   
fp_bucketsr\  r  r]  r^  r_  r`  r   r   r   re    s2   



re  c              	   C   s   t d| |||jd}| }ttjd|dd}td|d ttj	|jd dtj	|jd	 dtj	|jd
 dgdd}t
j|  d| ||d}|S )Nr   )rT   r   r$  json_configr   meshrU   rX   rX  r   rM  r   r   rN  rY  r   r<  )r   r   ry   r	   rx   r
   r   r   r   rS  r   rp   )rZ   r   r$  rq  mesh_plugin_datarW   r   tensor_summaryr   r   r   _get_tensor_summary<  s8   ru  c           
      C   sf   dd l }g }|df|df|dfg}|D ]\}}	|d u rq|t| t||	|j|dd qt|dS )Nr   r   r   r   T)	sort_keysr\   )rQ  ro   ru  r   dumpsr   )
rZ   verticescolorsfacesconfig_dictrQ  	summariestensorsr   r$  r   r   r   rr  Y  s   
rr  )r   r   r   )NN)r   r   )N)r   r   )r   r   N)r   NN)r   r   )r  )rT  N)6loggingr  re_renumpyr(   protor   proto.plugin_mesh_pb2r   proto.plugin_pr_curve_pb2r   proto.plugin_text_pb2r   proto.summary_pb2r   r   r	   proto.tensor_pb2r
   proto.tensor_shape_pb2r   utilsr   r   r   x2numr   	getLoggerrQ   r   compiler   r   rB   rL   r   r   r   r   r,   r   r   r   r   r   r%  r6  r+   rd  rg  re  ru  rr  r   r   r   r   <module>   sH    




N


.
 



D 


