o
    hZ                     @   sj  d dl Z d dlZd dlZd dlmZ d dlZd dl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 d dlmZ d d	lmZ d
dlmZ d
dlmZmZ g dZeeZ i ej!dej"dej#dej$dej%dej&dej'dej(dej)dej*dej+dej,dej-dej.dej/dej0dej1dej2dej3dej4dej5dej6dej7dej)dej8dej9di	Z:dd Z;			dRd d!Z<dSd"d#Z=dTd%d&Z>d'd( Z?d)d* Z@dUd+d,ZAdUd-d.ZBdVd0d1ZC	dWd3d4ZDdUd5d6ZEdXd7d8ZFdYd:d;ZGd<d= ZHdZd?d@ZIdAdB ZJdCdD ZK	d[dFdGZLd[dHdIZMd\dJdKZNdLdM ZOdNdO ZP	d\dPdQZQdS )]    N)Optional)
struct_pb2)HistogramProtoSummarySummaryMetadata)TensorProto)TensorShapeProto)
layout_pb2)PrCurvePluginData)TextPluginData   )make_np)_prepare_videoconvert_to_HWC)hparamsscalarhistogram_raw	histogrammake_histogramimageimage_boxes
draw_boxes
make_imagevideo
make_videoaudiocustom_scalarstexttensor_protopr_curve_rawpr_curvecompute_curvemesh)DT_HALFhalf_val)	DT_BFLOAT	float_val)DT_FLOATr&   )	DT_DOUBLE
double_val)DT_INT8int_val)DT_UINT8r+   )DT_INT16r+   )DT_INT32r+   )DT_INT64	int64_val)DT_COMPLEX32scomplex_val)DT_COMPLEX64r2   )DT_BOOLbool_val)DT_COMPLEX128dcomplex_val)r,   
uint32_valc                 C   s,   t | tjs
|  n| }|jtjkrdS dS )Nr      )
isinstancenpndarraynumpydtypeuint8)tensor	converted rB   U/var/www/html/ai/venv/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py_calc_scale_factorR   s   rD   black   c	                 C   s   ddl m}	m}
 |
 }|	| }||||f\}}}}|j||f||f||f||f||fg||d |rj|}||\}}td| }|j	||| d|  f|| |fg|d |j
|| || | f|||d | S )Nr   )	ImageDraw	ImageFont)widthfillg?rF   )rJ   )rJ   font)PILrG   rH   load_defaultDrawlinegetsizer;   ceil	rectangler   )r   xminyminxmaxymaxdisplay_strcolor
color_text	thicknessrG   rH   rK   drawleftrighttopbottomtext_bottom
text_widthtext_heightmarginrB   rB   rC   _draw_single_boxW   s4   
 
rd   c                    sj  ddl }ddlm}m}m}m mm} ddlm	}m
}	m}
m}m} ddlm}m}m} tts:td tdt|tsHtd td|pKi }t|tsUtd| D ]$\}vsrt|trrtfd	d
|D s}td d dqYg }| } D ]\}|du rqt|ttfr||j _|v rtjdd | D d}nd}| ||!d|d qt|t"r||j _#|v rtjdd | D d}nd}| ||!d|d qt|t$r||j _%|v rtjdd | D d}nd}| ||!d|d qt||j&r;t'|d }||j _| ||!dd qt(d|||	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 )$a2  Outputs three `Summary` protocol buffers needed by hparams plugin.
    `Experiment` keeps the metadata of an experiment, such as the name of the
      hyperparameters and the name of the metrics.
    `SessionStartInfo` keeps key-value pairs of the hyperparameters
    `SessionEndInfo` describes status of the experiment e.g. STATUS_SUCCESS

    Args:
      hparam_dict: A dictionary that contains names of the hyperparameters
        and their values.
      metric_dict: A dictionary that contains names of the metrics
        and their values.
      hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that
        contains names of the hyperparameters and all discrete values they can hold

    Returns:
      The `Summary` protobufs for Experiment, SessionStartInfo and
        SessionEndInfo
    r   N)DataType
Experiment
HParamInfo
MetricInfo
MetricNameStatus)EXPERIMENT_TAGPLUGIN_DATA_VERSIONPLUGIN_NAMESESSION_END_INFO_TAGSESSION_START_INFO_TAG)HParamsPluginDataSessionEndInfoSessionStartInfoz>parameter: hparam_dict should be a dictionary, nothing logged.z>parameter: metric_dict should be a dictionary, nothing logged.zIparameter: hparam_domain_discrete should be a dictionary, nothing logged.c                 3   s"    | ]}t |t  V  qd S N)r:   type.0d)hparam_dictkrB   rC   	<genexpr>   s     zhparams.<locals>.<genexpr>z"parameter: hparam_domain_discrete[z/] should be a list of same type as hparam_dict[z].c                 S      g | ]}t j|d qS ))number_valuer   Valueru   rB   rB   rC   
<listcomp>       
zhparams.<locals>.<listcomp>)valuesDATA_TYPE_FLOAT64)namert   domain_discretec                 S   r{   ))string_valuer}   ru   rB   rB   rC   r      r   DATA_TYPE_STRINGc                 S   r{   ))
bool_valuer}   ru   rB   rB   rC   r     r   DATA_TYPE_BOOL)r   rt   z=value should be one of int, float, str, bool, or torch.Tensor)session_start_infoversionplugin_namecontentplugin_data)tagmetadatavaluec                    s   g | ]
} |d dqS )r   )r   rB   )rv   ry   )rh   ri   rB   rC   r   %      )hparam_infosmetric_infos)
experimentr   STATUS_SUCCESS)status)session_end_infor   ).torch#tensorboard.plugins.hparams.api_pb2re   rf   rg   rh   ri   rj   $tensorboard.plugins.hparams.metadatark   rl   rm   rn   ro   +tensorboard.plugins.hparams.plugin_data_pb2rp   rq   rr   r:   dictloggerwarning	TypeErroritemslistallintfloatr   r|   r   	ListValueappendr~   strr   boolr   Tensorr   
ValueErrorr   
PluginDataSerializeToStringr   keys)rx   metric_dicthparam_domain_discreter   re   rf   rg   rj   rk   rl   rm   rn   ro   rp   rq   rr   vhpsssir   r   smdmtsexpseirB   )rh   ri   rx   ry   rC   r      s    







r   Fc           	      C   s   t | }|jdksJ d|j d|j dt|}|rEt|gdd}|r.t|gdd}tjd	d
}t|d}ttj	| ||dgdS 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.
      collections: Optional list of graph collections keys. The new summary op is
        added to these collections. Defaults to `[GraphKeys.SUMMARIES]`.
      new_style: Whether to use new style (tensor field) or old style (simple_value
        field). New style could lead to faster data loading.
    Returns:
      A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf.
    Raises:
      ValueError: If tensor has the wrong shape or type.
    r   zBTensor should contain one element (0 dimensions). Was given size: z and z dimensions.r'   )r&   r>   r(   )r)   r>   scalarsr   r   r   r@   r   r   )r   simple_value)
r   squeezendimsizer   r   r   r   r   r~   )	r   r@   collections	new_styledouble_precisionr   r   r   r   rB   rB   rC   r   =  s(   

r   c                    s      j dkrtd jtv rit j d }|dks!|dkr+t   }n   dkr7 	 g}n   dkr@g }n   }dt j d dt
 fd	d
t  D d||i}tdi |}n
t|  d j tjdd}t|d}ttj| ||dgdS )a  Outputs a `Summary` protocol buffer containing the full tensor.
    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: Tensor to be converted to protobuf
    Returns:
      A tensor protobuf in a `Summary` protobuf.
    Raises:
      ValueError: If tensor is too big to be converted to protobuf, or
                     tensor data type is not supported
    l        zAtensor is bigger than protocol buffer's hard limit of 2GB in sizer   r2   r7   r   r>   tensor_shapec                    s   g | ]}t j j| d qS )r   )r   Dimshape)rv   ir@   rB   rC   r     s    z tensor_proto.<locals>.<listcomp>dimz has unsupported tensor dtype r@   r   r   r   r   r@   r   NrB   )numelitemsizer   r>   _TENSOR_TYPE_MAPr   view_as_realflattentolistitemr   ranger   r   r   r   r   r~   )r   r@   proto_val_fieldproto_val_contentstensor_proto_argsr   r   r   rB   r   rC   r   g  s4   



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r   histor   )r   r   r~   )	r   r   r   r   r   r   bucket_limitsbucket_countshistrB   rB   rC   r     s   	r   c                 C   s0   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   astyper   r   r~   )r   r   binsmax_binsr   rB   rB   rC   r     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   r]   )sidez1The histogram is empty, please file a bug report.r   )r   r   reshaper;   r   lenpadr   emptyr>   cumsumgreatersearchsortedr   concatenatedotr   r   r   r   )r   r   r   countslimitsnum_binssubsamplingsubsampling_remainder
new_limits
cum_countsstartendsum_sqrB   rB   rC   r     sP   

 .
r   NCHWc                 C   s`   t |}t||}t|}|tj}|| ddtj}t||d}t	t	j
| |dgdS )aJ  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.
    The `name` in the outputted Summary.Value protobufs is generated based on the
    name, with a suffix depending on the max_outputs setting:
    *  If `max_outputs` is 1, the summary value tag is '*name*/image'.
    *  If `max_outputs` is greater than 1, the summary value tags are
       generated sequentially as '*name*/image/0', '*name*/image/1', etc.
    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). Out-of-range values
        will be clipped.
    Returns:
      A scalar `Tensor` of type `string`. The serialized `Summary` protocol
      buffer.
    r   r9   )rescaler   r   r   )r   r   rD   r   r;   float32clipr?   r   r   r~   )r   r@   r  dataformatsscale_factorr   rB   rB   rC   r     s   
r   CHWc                 C   sd   t |}t||}t |}|tjt| }t|ddtj|||d}t	t	j
| |dgdS )z0Outputs a `Summary` protocol buffer with images.r   r9   )r  roislabelsr  r   )r   r   r   r;   r  rD   r   r  r?   r   r~   )r   tensor_imagetensor_boxesr  r  r  r   rB   rB   rC   r   *  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   rF      Red)rW   rX   )r   r   rd   )
disp_imageboxesr  	num_boxeslist_gtr   rB   rB   rC   r   ;  s   




	r   c                 C   s   ddl m} | j\}}}t|| }t|| }	|| }
|dur(t|
||d}
z|jj}W n ty:   |j	}Y nw |

|	|f|}
ddl}| }|
j|dd | }|  tj||||dS )z<Convert a numpy representation of an image to Image protobufr   )ImageN)r  PNG)formatheightrI   
colorspaceencoded_image_string)rL   r  r   r   	fromarrayr   
ResamplingLANCZOSAttributeError	ANTIALIASresizeioBytesIOsavegetvaluecloser   )r@   r  r  r  r  r  rI   channelscaled_heightscaled_widthr   r   r"  outputimage_stringrB   rB   rC   r   L  s0   

r      c                 C   s\   t |}t|}t|}|tj}|| ddtj}t||}t	t	j
| |dgdS )Nr   r9   r  r   )r   r   rD   r   r;   r  r  r?   r   r   r~   )r   r@   fpsr	  r   rB   rB   rC   r   i  s   
r   c                 C   s`  zdd l }W n ty   td Y d S w zddl m} W n ty,   tdd Y d S w dd l}| j\}}}}|jt| |d}	|jddd	j	}
z
|	j
|
dd d
 W n$ tyw   z
|	j
|
ddd W n tyt   |	j
|
dd Y nw Y nw t|
d}| }W d    n1 sw   Y  zt|
 W n ty   td Y nw tj||||dS )Nr   zadd_video needs package moviepy)editorz6moviepy is installed, but can't import moviepy.editor.z2Some packages could be missing [imageio, requests])r-  z.gifF)suffixdelete)verboser   )r1  progress_bar)r1  rbz5The temporary file used by moviepy cannot be deleted.r  )moviepyImportErrorprintr.  tempfiler   ImageSequenceClipr   NamedTemporaryFiler   	write_gifr   openreadosremoveOSErrorr   r   r   r  )r@   r-  r4  mpyr7  thwcr  filenameftensor_stringrB   rB   rC   r   t  sP   
r   D  c           
      C   s  t |}| }t| dkrtd |dd}|jdks#J d|ttj	j 
d}dd l}dd l}| }||d}|d |d || ||j W d    n1 saw   Y  | }|  tj|d|jd |d	d
}	ttj| |	dgdS )Nr   z4warning: audio amplitude out of range, auto clipped.r   z%input tensor should be 1 dimensional.z<i2r   wbrF   z	audio/wav)sample_ratenum_channelslength_framesencoded_audio_stringcontent_type)r   r   r   )r   r   absr   r6  r  r   r;   iinfoint16r   r"  waver#  r;  setnchannelssetsampwidthsetframeratewriteframesdatar%  r&  r   Audior   r~   )
r   r@   rJ  arrayr"  rR  fio
wave_writeaudio_stringr   rB   rB   rC   r     s4   


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  rF   )r   lowerupper)series)titlerc   r   )ra  	multiline)ra  chart)categoryr   r   r   	DT_STRINGr>   
string_valr   custom_scalars__config__r   r   )r   r   r	   MarginChartContentSeriesChartMultilineChartContentr   CategoryLayoutr   r   r   r   r   r   r~   )layout
categoriesry   r   charts
chart_namechart_meatadatatagsmgccrc  mlccr   r   r@   rB   rB   rC   r     s<   
r   c                 C   sf   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   r   r   re  utf_8)encodingr   r   r   rf  z/text_summaryr   r   )
r   r   r   r   r   encoder   r   r   r~   )r   r   r   r   r@   rB   rB   rC   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 )Nrz  r   r   num_thresholds	pr_curvesr   r   r'   r   r   r   r   r>   r&   r   r   r   )r;   stackr
   r   r   r   r   r   r   r   r   r   r   r~   )r   tpfptnfn	precisionrecallr|  weightsrW  pr_curve_plugin_datar   r   r@   rB   rB   rC   r     s,   

r   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 )Nrz  )r|  r  r   r{  r}  r   r   r'   r   r   r   r   r~  r   r   )r   r!   r
   r   r   r   r   r   r   r   r   r   r   r~   )
r   r  predictionsr|  r  rW  r  r   r   r@   rB   rB   rC   r      s.   


r    c                 C   s
  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 ||||||fS )NgHz>g      ?r   r   )r   r   r  r   )	r;   int32floorr   float64r   r   maximumr  )r  r  r|  r  _MINIMUM_COUNTbucket_indicesfloat_labelshistogram_range
tp_buckets_
fp_bucketsr  r  r  r  r  r  rB   rB   rC   r!   &  s2   


r!   c              	   C   s   ddl }ddlm} ||}|j| ||||j||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}
|
S )a  Creates a tensor summary with summary metadata.

    Args:
      name: Uniquely identifiable name of the summary op. Could be replaced by
        combination of name and type to make it unique even outside of this
        summary.
      display_name: Will be used as the display name in TensorBoard.
        Defaults to `name`.
      description: A longform readable description of the summary data. Markdown
        is supported.
      tensor: Tensor to display in summary.
      content_type: Type of content inside the Tensor.
      components: Bitmask representing present parts (vertices, colors, etc.) that
        belong to the summary.
      json_config: A string, JSON-serialized dictionary of ThreeJS classes
        configuration.

    Returns:
      Tensor summary with metadata.
    r   Nr   )json_configr'   r   r   r   rF   r   r~  r   )r   tensorboard.plugins.meshr   	as_tensorcreate_summary_metadatar   r   r   r   r   r   r   r~   get_instance_name)r   display_namedescriptionr@   rN  
componentsr  r   r   tensor_metadatatensor_summaryrB   rB   rC   _get_tensor_summaryG  s8   


r  c                 C   s   d}| durt j| dd}|S )z6Parses and returns JSON string from python dictionary.z{}NT)	sort_keys)jsondumps)config_dictr  rB   rB   rC   _get_json_config  s   r  c                 C   s   ddl m} ddlm} t|}	g }
||jf||jf||jfg}dd |D }|dd |D }|D ]\}}|
	t
| ||||||	 q3t|
dS )a(  Outputs a merged `Summary` protocol buffer with a mesh/point cloud.

    Args:
      tag: A name for this summary operation.
      vertices: Tensor of shape `[dim_1, ..., dim_n, 3]` representing the 3D
        coordinates of vertices.
      faces: Tensor of shape `[dim_1, ..., dim_n, 3]` containing indices of
        vertices within each triangle.
      colors: Tensor of shape `[dim_1, ..., dim_n, 3]` containing colors for each
        vertex.
      display_name: If set, will be used as the display name in TensorBoard.
        Defaults to `name`.
      description: A longform readable description of the summary data. Markdown
        is supported.
      config_dict: Dictionary with ThreeJS classes names and configuration.

    Returns:
      Merged summary for mesh/point cloud representation.
    r   r  )MeshPluginDatac                 S   s   g | ]
}|d  dur|qS )r   NrB   )rv   r@   rB   rB   rC   r     r   zmesh.<locals>.<listcomp>c                 S   s   g | ]\}}|qS rB   rB   )rv   r@   rN  rB   rB   rC   r     s    r   )r  r   (tensorboard.plugins.mesh.plugin_data_pb2r  r  VERTEXFACECOLORget_components_bitmaskr   r  r   )r   verticescolorsfacesr  r  r  r   r  r  	summariestensorsr  r@   rN  rB   rB   rC   r"     s2   
r"   )rE   rE   rF   )NNN)NFFrs   )r   r  )r   r
  N)r   NN)r,  )rH  )rz  N)NN)Rr  loggingr=  typingr   r   r=   r;   google.protobufr   $tensorboard.compat.proto.summary_pb2r   r   r   #tensorboard.compat.proto.tensor_pb2r   )tensorboard.compat.proto.tensor_shape_pb2r   !tensorboard.plugins.custom_scalarr	   ,tensorboard.plugins.pr_curve.plugin_data_pb2r
   (tensorboard.plugins.text.plugin_data_pb2r   _convert_npr   _utilsr   r   __all__	getLogger__name__r   halffloat16bfloat16r  r   r  doubleint8r?   qint8rQ  shortr   r  qint32int64	complex32chalf	complex64cfloatr   
complex128cdoublequint8quint4x2r   rD   rd   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r  r  r"   rB   rB   rB   rC   <module>   s    
	


* 
=*3
 

7%




+%


!;
