o
    NeM                     @   sB  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z
ddlZddlm  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	d
Zd+ddZedG dd dZdd Zd,ddZdd Zdd Zdd Z dd Z!	d-ddZ"d d! Z#d"d# Z$d$d% Z%G d&d' d'e
j&Z'G d(d) d)Z(dS ).z#Python utilities required by Keras.    N)serialization_lib)io_utils)
tf_inspect)keras_exportc                 C   s   t jdkrt| jdd}t|dd}nt| j}t|dd}| j	}| j
r9tdd | j
D }nd}|||fS )	zSerializes a user defined function.

    Args:
        func: the function to serialize.

    Returns:
        A tuple `(code, defaults, closure)`.
    nt   \   /base64asciic                 s   s    | ]}|j V  qd S N)cell_contents).0c r   ID:\Projects\ConvertPro\env\Lib\site-packages\keras/utils/generic_utils.py	<genexpr>7   s    zfunc_dump.<locals>.<genexpr>N)osnamemarshaldumps__code__replacecodecsencodedecode__defaults____closure__tuple)funcraw_codecodedefaultsclosurer   r   r   	func_dump&   s   
	
r#   c              	      s   t | ttfr| \} }}t |trt|}dd  |dur(t fdd|D }zt| dd}W n ttjfyD   | d}Y nw t	
|} |du rQt }tj| || j||d	S )
a	  Deserializes a user defined function.

    Args:
        code: bytecode of the function.
        defaults: defaults of the function.
        closure: closure of the function.
        globs: dictionary of global objects.

    Returns:
        A function object.
    c                    s,    fdd}|j d }t t|s|S  S )zEnsures that a value is converted to a python cell object.

        Args:
            value: Any value that needs to be casted to the cell type

        Returns:
            A value wrapped as a cell object (see function "func_load")
        c                      s     d S r   r   r   valuer   r   dummy_fnX   s   z9func_load.<locals>.ensure_value_to_cell.<locals>.dummy_fnr   )r   
isinstancetype)r%   r&   Z
cell_valuer   r$   r   ensure_value_to_cellN   s
   

z'func_load.<locals>.ensure_value_to_cellNc                 3   s    | ]} |V  qd S r   r   )r   _r)   r   r   r   b   s    zfunc_load.<locals>.<genexpr>r
   r	   Zraw_unicode_escape)r   Zargdefsr"   )r'   r   listr   r   r   UnicodeEncodeErrorbinasciiErrorr   loadsglobalspython_typesFunctionTypeco_name)r    r!   r"   Zglobsr   r   r+   r   	func_load=   s$   


r5   Fc                 C   s0   t | }|r|jdurdS ||jv p||jv S )a  Checks if a callable accepts a given keyword argument.

    Args:
        fn: Callable to inspect.
        name: Check if `fn` can be called with `name` as a keyword argument.
        accept_all: What to return if there is no parameter called `name` but
          the function accepts a `**kwargs` argument.

    Returns:
        bool, whether `fn` accepts a `name` keyword argument.
    NT)r   getfullargspecvarkwargs
kwonlyargs)fnr   Z
accept_allZarg_specr   r   r   has_argo   s   
r;   zkeras.utils.Progbarc                   @   sP   e Zd ZdZ					dddZdd	d
ZdddZdd Zdd Zdd Z	dS )Progbara[  Displays a progress bar.

    Args:
        target: Total number of steps expected, None if unknown.
        width: Progress bar width on screen.
        verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)
        stateful_metrics: Iterable of string names of metrics that should *not*
          be averaged over time. Metrics in this list will be displayed as-is.
          All others will be averaged by the progbar before display.
        interval: Minimum visual progress update interval (in seconds).
        unit_name: Display name for step counts (usually "step" or "sample").
          皙?Nstepc                 C   s   || _ || _|| _|| _|| _|rt|| _nt | _ttj	dr&tj	
 p4dtjv p4dtjv p4dtjv | _d| _d| _i | _g | _t | _d| _| j| _d | _d | _d S )NisattyZ	ipykernelposixZPYCHARM_HOSTEDr   )targetwidthverboseinterval	unit_namesetstateful_metricshasattrsysstdoutrA   modulesr   environ_dynamic_display_total_width_seen_so_far_values_values_ordertime_start_last_update_time_at_epoch_start_time_at_epoch_end_time_after_first_step)selfrC   rD   rE   rF   rI   rG   r   r   r   __init__   s0   	

zProgbar.__init__c                 C   s  |du r| j du rd}n|| j k}|pg }|D ]K\}}|| jvr&| j| || jvr[t|| j d}|| jvrB|| |g| j|< q| j| d  || 7  < | j| d  |7  < q|dg| j|< q|| _d}t }d|| j dd}	|| j kr~|| _	| j
dkr|| j | jk r|sdS | j}
| jr|d	|
 7 }|d
7 }n|d7 }| j durtt| j d }dt| d || j f }t|| j  }t| j| }|dkr|d|d  7 }|| j k r|d7 }n|d7 }|d| j|  7 }|d7 }nd| }t|| _||7 }| ||}| j du s|r|	| || j7 }	n5|| j |  }|dkr9d|d |d d |d f }n|dkrId|d |d f }nd| }d| }	| jD ]M}|	d| d7 }	t| j| trt| j| d td| j| d  }t|dkr|	d|d7 }	qU|	d|d7 }	qU|	d| j|  7 }	qU|  jt|	7  _|
| jkr|	d|
| j  7 }	|r|	d7 }	||	7 }tj|dd d}n| j
dkri|ritt| j d }dt| d  || j f }||	 }	| jD ]6}|	d| d7 }	t| j| d td| j| d  }|dkr$|	d|d7 }	q|	d|d7 }	q| j	r\| j	| j }|| j  }|| _d| _	|	d!| |d" 7 }	|	d!| || j 7 }	|	d7 }	||	7 }tj|dd d}|| _dS )#a  Updates the progress bar.

        Args:
            current: Index of current step.
            values: List of tuples: `(name, value_for_last_step)`. If `name` is
              in `stateful_metrics`, `value_for_last_step` will be displayed
              as-is. Else, an average of the metric over time will be
              displayed.
            finalize: Whether this is the last update for the progress bar. If
              `None`, defaults to `current >= self.target`.
        NFr>   r    z - .0fs
%zd/%d [=>.]z%7d/Unknowni  z%d:%02d:%02d<   z%d:%02dz%dsz - ETA: :MbP? z.4fz.4e)Z
line_break   zd/%dz -epoch) rC   rS   appendrI   maxrQ   rR   rT   rU   rX   rE   rV   rF   rP   rO   intnplog10strfloatrD   len_estimate_step_duration_format_timerG   r'   r,   meanabsr   Z	print_msgrW   )rZ   currentvaluesfinalizekvZ
value_basemessagenowinfoZprev_total_widthZ	numdigitsbarprogZ
prog_widthtime_per_unitetaZ
eta_formatZavgcountZtime_per_epochZavg_time_per_stepr   r   r   update   s   
















 
 



zProgbar.updatec                 C   s   |  | j| | d S r   )r   rQ   )rZ   nrz   r   r   r   addL  s   zProgbar.addc                 C   sr   d}|dks
|dkr|d|dd| 7 }|S |dkr*|d|d dd	| 7 }|S |d|d
 dd| 7 }|S )a  format a given duration to display to the user.

        Given the duration, this function formats it in either milliseconds
        or seconds and displays the unit (i.e. ms/step or s/epoch)
        Args:
          time_per_unit: the duration to display
          unit_name: the name of the unit to display
        Returns:
          a string with the correctly formatted duration and units
        r\   r>   r   rj   r]   zs/ri   g     @@zms/g    .Azus/r   )rZ   r   rG   	formattedr   r   r   rv   O  s   zProgbar._format_timec                 C   sN   |r%| j dur|dkr|| j  |d  }n|| j | }|dkr#|| _ |S dS )a  Estimate the duration of a single step.

        Given the step number `current` and the corresponding time `now` this
        function returns an estimate for how long a single step takes. If this
        is called before one step has been completed (i.e. `current == 0`) then
        zero is given as an estimate. The duration estimate ignores the duration
        of the (assumed to be non-representative) first step for estimates when
        more steps are available (i.e. `current>1`).

        Args:
          current: Index of current step.
          now: The current time.

        Returns: Estimate of the duration of a single step.
        Nr>   r   )rY   rU   )rZ   ry   r   r   r   r   r   ru   c  s   zProgbar._estimate_step_durationc                 C   s   | j || _ d S r   )rI   union)rZ   rI   r   r   r   _update_stateful_metrics  s   z Progbar._update_stateful_metrics)r=   r>   r?   Nr@   NNr   )
__name__
__module____qualname____doc__r[   r   r   rv   ru   r   r   r   r   r   r<      s    

% 
$r<   c                    s0   t tt  } fddtd|D S )zReturns a list of batch indices (tuples of indices).

    Args:
        size: Integer, total size of the data to slice into batches.
        batch_size: Integer, batch size.

    Returns:
        A list of tuples of array indices.
    c                    s&   g | ]}|  t |d    fqS )r>   )min)r   i
batch_sizesizer   r   
<listcomp>  s    z make_batches.<locals>.<listcomp>r   )ro   rp   ceilrs   range)r   r   Znum_batchesr   r   r   make_batches  s   
r   c                    s   | du rdgS t  trdurtd  d t | tr@t dr6t dr-    fdd| D S  fdd| D S t drRt drN   |   S t d	r]|   S dgS )
a  Slice an array or list of arrays.

    This takes an array-like, or a list of
    array-likes, and outputs:
        - arrays[start:stop] if `arrays` is an array-like
        - [x[start:stop] for x in arrays] if `arrays` is a list

    Can also work on list/array of indices: `slice_arrays(x, indices)`

    Args:
        arrays: Single array or list of arrays.
        start: can be an integer index (start index) or a list/array of indices
        stop: integer (stop index); should be None if `start` was a list.

    Returns:
        A slice of the array(s).

    Raises:
        ValueError: If the value of start is a list and stop is not None.
    NzQThe stop argument has to be None if the value of start is a list. Received start=z, stop=__len__shapec                    s    g | ]}|d u r
d n|  qS r   r   r   x)startr   r   r     s     z slice_arrays.<locals>.<listcomp>c                    s2   g | ]}|d u r
d nt |dsd n|  qS )N__getitem__)rJ   r   r   stopr   r   r     s    
r   )r'   r,   
ValueErrorrJ   tolist)Zarraysr   r   r   r   r   slice_arrays  s2   



	

r   c                 C   s   t | tr| S | gS )zNormalizes a list/tensor into a list.

    If a tensor is passed, we return
    a list of size 1 containing the tensor.

    Args:
        x: target object to be normalized.

    Returns:
        A list.
    )r'   r,   )r   r   r   r   to_list  s   
r   c                 C   s8   t dd| }t dd| }|d dkr|S d| S )Nz(.)([A-Z][a-z]+)z\1_\2z([a-z])([A-Z])r   r*   private)resublower)r   ZintermediateZinsecurer   r   r   to_snake_case  s
   r   c                 C   s(   t j| }|D ]	}|d ur dS qdS )NFT)tfnestflatten)Z	structureiterableelementr   r   r   is_all_none  s   r   c                 C   s8   t | |}|rtd|  dt| d| d S )NzUnknown entries in z dictionary: z . Only expected following keys: )rH   keys
differencer   r,   )r   Z
input_dictZexpected_valuesunknownr   r   r   check_for_unexpected_keys  s   r    Keyword argument not understood:c                 C   s    | D ]}||vrt ||qdS )zAChecks that all keyword arguments are in the set of allowed keys.N)	TypeError)kwargsZallowed_kwargserror_messagekwargr   r   r   validate_kwargs  s
   
r   c                 C   s
   d| _ | S )z5Decorates a method to detect overrides in subclasses.T)_is_defaultmethodr   r   r   default  s   r   c                 C   s   t | ddS )z:Check if a method is decorated with the `default` wrapper.r   F)getattrr   r   r   r   
is_default  s   r   c                 C   s6   |D ]}t |D ]}t||}||r|| |< qqd S r   )dirr   )target_dictrM   Z
obj_filtermoduler   objr   r   r   !populate_dict_with_module_objects  s   
r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )
LazyLoaderzFLazily import a module, mainly to avoid pulling in large dependencies.c                    s   || _ || _t | d S r   )_local_name_parent_module_globalssuperr[   )rZ   Z
local_nameZparent_module_globalsr   	__class__r   r   r[     s   zLazyLoader.__init__c                 C   s*   t | j}|| j| j< | j|j |S )z8Load the module and insert it into the parent's globals.)	importlibimport_moduler   r   r   __dict__r   )rZ   r   r   r   r   _load!  s   zLazyLoader._loadc                 C   s   |   }t||S r   )r   r   )rZ   itemr   r   r   r   __getattr__,  s   
zLazyLoader.__getattr__)r   r   r   r   r[   r   r   __classcell__r   r   r   r   r     s
    r   c                   @   s   e Zd Zdd Zdd ZdS )Configc                 K   s
   || _ d S r   )config)rZ   r   r   r   r   r[   2  s   
zConfig.__init__c                 C   s   t | jS r   )r   Zserialize_keras_objectr   )rZ   r   r   r   	serialize5  s   zConfig.serializeN)r   r   r   r[   r   r   r   r   r   r   1  s    r   )NNN)Fr   )r   ))r   r.   r   r   r   r   r   rK   rT   typesr2   numpyrp   Ztensorflow.compat.v2compatv2r   Zkeras.saving.experimentalr   Zkeras.utilsr   r   Z tensorflow.python.util.tf_exportr   r#   r5   r;   r<   r   r   r   r   r   r   r   r   r   r   
ModuleTyper   r   r   r   r   r   <module>   sH   

2  
4
	

	