o
    2h+                     @   s   d 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	 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 Zdd ZG dd dejZG dd dejZ								dddZdS )z?Contains functions for evaluation and summarization of metrics.    N)dtypes)ops)	array_ops)init_ops)math_ops)	state_ops)variable_scope)
tf_logging)basic_session_run_hooks)monitored_session)session_run_hookc                  C   sj   t  } | t jj}t|dkr|d S t|dkrtdtjdg t	j
t dt jjt jjgd}|S )zGets or creates the eval step `Tensor`.

  Returns:
    A `Tensor` representing a counter for the evaluation step.

  Raises:
    ValueError: If multiple `Tensors` have been added to the
      `tf.GraphKeys.EVAL_STEP` collection.
     r   z0Multiple tensors added to tf.GraphKeys.EVAL_STEP	eval_stepF)shapedtypeinitializer	trainablecollections)r   get_default_graphget_collection	GraphKeys	EVAL_STEPlen
ValueErrorr   get_variabler   int64r   zeros_initializerLOCAL_VARIABLES)graph
eval_stepscounter r!   `/var/www/html/chatgem/venv/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py_get_or_create_eval_step!   s   
r#   c                 C   sT   t | trt|  } t|  tt 	 W  d   S 1 s#w   Y  dS )a  Gets the eval step `Tensor` value after running `update_ops`.

  Args:
    update_ops: A list of `Tensors` or a dictionary of names to `Tensors`, which
      are run before reading the eval step value.

  Returns:
    A `Tensor` representing the value for the evaluation step.
  N)

isinstancedictlistvaluesr   control_dependenciesr   identityr#   
read_value)
update_opsr!   r!   r"   _get_latest_eval_step_value<   s
   

$r,   c                   @   sB   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dS )_MultiStepStopAfterNEvalsHookGRun hook used by the evaluation routines to run the `eval_ops` N times.r   c                 C   s   || _ d| _|| _dS )zConstructs the run hook.

    Args:
      num_evals: The number of evaluations to run for. if set to None, will
        iterate the dataset until all inputs are exhausted.
      steps_per_run: Number of steps executed per run call.
    N)
_num_evals_evals_completed_steps_per_run_initial_value)self	num_evalssteps_per_runr!   r!   r"   __init__P   s   
z&_MultiStepStopAfterNEvalsHook.__init__c                 C   
   || _ d S Nr0   r2   updated_eval_stepr!   r!   r"   _set_evals_completed_tensor\      
z9_MultiStepStopAfterNEvalsHook._set_evals_completed_tensorc                 C   s   t  | _d S r7   )r
   $get_or_create_steps_per_run_variable_steps_per_run_variable)r2   r!   r!   r"   begin_   s   z#_MultiStepStopAfterNEvalsHook.beginc                 C   s4   | j d u r	| j}nt| j| j }| jj||d d S )Nsession)r/   r1   minr>   load)r2   rA   coordstepsr!   r!   r"   after_create_sessionc   s   
z2_MultiStepStopAfterNEvalsHook.after_create_sessionc                 C      t d| jiS Nevals_completedr   SessionRunArgsr0   r2   run_contextr!   r!   r"   
before_runk      z(_MultiStepStopAfterNEvalsHook.before_runc                 C   s   |j d }| jd u r| j}n	t| j| | j}| jj||jd | jd u r,td| ntd|| j | jd urD|| jkrF|	  d S d S d S )NrI   r@   Evaluation [%d]Evaluation [%d/%d])
resultsr/   r1   rB   r>   rC   rA   logginginforequest_stop)r2   rM   
run_valuesrI   rE   r!   r!   r"   	after_runo   s   



z'_MultiStepStopAfterNEvalsHook.after_runN)r   )
__name__
__module____qualname____doc__r5   r;   r?   rF   rN   rW   r!   r!   r!   r"   r-   M   s    
r-   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )_StopAfterNEvalsHookr.   Tc                 C   s@   || _ d| _|| _|du s|dk rd| _dS t|d | _dS )zConstructs the run hook.

    Args:
      num_evals: The number of evaluations to run for. if set to None, will
        iterate the dataset until all inputs are exhausted.
      log_progress: Whether to log evaluation progress, defaults to True.
    N   r   g      $@)r/   r0   _log_progressmathfloor_log_frequency)r2   r3   log_progressr!   r!   r"   r5      s   	z_StopAfterNEvalsHook.__init__c                 C   r6   r7   r8   r9   r!   r!   r"   r;      r<   z0_StopAfterNEvalsHook._set_evals_completed_tensorc                 C   rG   rH   rJ   rL   r!   r!   r"   rN      rO   z_StopAfterNEvalsHook.before_runc                 C   sx   |j d }| jr(| jd u rtd| n|| j dks | j|kr(td|| j | jd ur8|| jkr:|  d S d S d S )NrI   rP   r   rQ   )rR   r^   r/   rS   rT   ra   rU   )r2   rM   rV   rI   r!   r!   r"   rW      s   


z_StopAfterNEvalsHook.after_runN)T)rX   rY   rZ   r[   r5   r;   rN   rW   r!   r!   r!   r"   r\      s    
r\    c	                 C   s  t  }	t|pg }|durctdd |D r)t }
tj|	tj|
|	j	ddd}ntj|	ddd}t
|tr;||d< nt
|ttfrJt||g }n||g}t|}|D ]}t
|ttfrb|| qTtd	td
t   t }tj|| ||d}t||}|| tj||d}|dur| s||| | rW d   n1 sw   Y  tdt |  tdtdt   |jS )ay	  Evaluates the model at the given checkpoint path.

  During a single evaluation, the `eval_ops` is run until the session is
  interrupted or requested to finish. This is typically requested via a
  `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running
  the requested number of times.

  Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of
  `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is
  evaluated a single time after `eval_ops` has finished running and the fetched
  values of `final_ops` are returned. If `final_ops` is left as `None`, then
  `None` is returned.

  One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record
  summaries after the `eval_ops` have run. If `eval_ops` is `None`, the
  summaries run immediately after the model checkpoint has been restored.

  Note that `evaluate_once` creates a local variable used to track the number of
  evaluations run via `tf.contrib.training.get_or_create_eval_step`.
  Consequently, if a custom local init op is provided via a `scaffold`, the
  caller should ensure that the local init op also initializes the eval step.

  Args:
    checkpoint_path: The path to a checkpoint to use for evaluation.
    master: The BNS address of the TensorFlow master.
    scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables
      and restoring variables. Note that `scaffold.init_fn` is used by the
      function to restore the checkpoint. If you supply a custom init_fn, then
      it must also take care of restoring the model from its checkpoint.
    eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to
      `Tensors`, which is run until the session is requested to stop, commonly
      done by a `tf.contrib.training.StopAfterNEvalsHook`.
    feed_dict: The feed dictionary to use when executing the `eval_ops`.
    final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names
      to `Tensors`.
    final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`.
    hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside
      the evaluation loop.
    config: An instance of `tf.compat.v1.ConfigProto` that will be used to
      configure the `Session`. If left as `None`, the default will be used.

  Returns:
    The fetched values of `final_ops` or `None` if `final_ops` is `None`.
  Nc                 s   s    | ]}t |tV  qd S r7   )r$   r-   ).0hr!   r!   r"   	<genexpr>   s    z!_evaluate_once.<locals>.<genexpr>)r   T)use_lockingr   update_eval_stepzStarting evaluation at z%Y-%m-%dT%H:%M:%S)scaffoldcheckpoint_filename_with_pathmasterconfig)session_creatorhookszInference Time : {:0.5f}szFinished evaluation at z%Y-%m-%d-%H:%M:%S)r#   r&   anyr
   r=   r   
assign_addr   castr   r$   r%   tupler,   r\   r-   r;   rS   rT   timestrftime	localtimer   ChiefSessionCreatorFinalOpsHookappendMonitoredSessionshould_stoprunformatfinal_ops_values)checkpoint_pathrk   ri   eval_ops	feed_dict	final_opsfinal_ops_feed_dictrn   rl   r   steps_per_run_variablerh   eval_step_valuere   startrm   final_ops_hookrA   r!   r!   r"   _evaluate_once   sf   5



r   )rc   NNNNNNN)r[   r_   rs   tensorflow.python.frameworkr   r   tensorflow.python.opsr   r   r   r   r   tensorflow.python.platformr	   rS   tensorflow.python.trainingr
   r   r   r#   r,   SessionRunHookr-   r\   r   r!   r!   r!   r"   <module>   s6   4(