U
    -eL+                     @   s  d Z dddg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	Z	 ddl
mZmZ ddlZeddd	d
dZG dd dejZG dd dejZedZde_eeZe Zee dddeeeeejf eddddZG dd dejZ dS )uo  
Logging utilities for dill.

The 'logger' object is dill's top-level logger.

The 'adapter' object wraps the logger and implements a 'trace()' method that
generates a detailed tree-style trace for the pickling call at log level INFO.

The 'trace()' function sets and resets dill's logger log level, enabling and
disabling the pickling trace.

The trace shows a tree structure depicting the depth of each object serialized
*with dill save functions*, but not the ones that use save functions from
'pickle._Pickler.dispatch'. If the information is available, it also displays
the size in bytes that the object contributed to the pickle stream (including
its child objects).  Sample trace output:

    >>> import dill, dill.tests
    >>> dill.detect.trace(True)
    >>> dill.dump_session(main=dill.tests)
    ┬ M1: <module 'dill.tests' from '.../dill/tests/__init__.py'>
    ├┬ F2: <function _import_module at 0x7f0d2dce1b80>
    │└ # F2 [32 B]
    ├┬ D2: <dict object at 0x7f0d2e98a540>
    │├┬ T4: <class '_frozen_importlib.ModuleSpec'>
    ││└ # T4 [35 B]
    │├┬ D2: <dict object at 0x7f0d2ef0e8c0>
    ││├┬ T4: <class '_frozen_importlib_external.SourceFileLoader'>
    │││└ # T4 [50 B]
    ││├┬ D2: <dict object at 0x7f0d2e988a40>
    │││└ # D2 [84 B]
    ││└ # D2 [413 B]
    │└ # D2 [763 B]
    └ # M1 [813 B]
adapterloggertrace    N)partial)TextIOUnion|+`)   │u   ├   ┬   └c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )TraceAdaptera  
    Tracks object tree depth and calculates pickled object size.

    A single instance of this wraps the module's logger, as the logging API
    doesn't allow setting it directly with a custom Logger subclass.  The added
    'trace()' method receives a pickle instance as the first argument and
    creates extra values to be added in the LogRecord from it, then calls
    'info()'.

    Usage of logger with 'trace()' method:

    >>> from dill.logger import adapter as logger  #NOTE: not dill.logger.logger
    >>> ...
    >>> def save_atype(pickler, obj):
    >>>     logger.trace(pickler, "Message with %s and %r etc. placeholders", 'text', obj)
    >>>     ...
    c                 C   s
   || _ d S N)r   )selfr    r   L/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/dill/logger.py__init__t   s    zTraceAdapter.__init__c                 C   s&   t d|d}|| | j| d S )Nz%(prefix)s%(message)s%(suffix)shandler)TraceFormattersetFormatterr   
addHandler)r   r   	formatterr   r   r   r   v   s    
zTraceAdapter.addHandlerc                 C   s   | j | d S r   )r   removeHandler)r   r   r   r   r   r   z   s    zTraceAdapter.removeHandlerc                 C   s   ||fS r   r   )r   msgkwargsr   r   r   process|   s    zTraceAdapter.processc                 C   s8   t jj|ddsd S | tjr.d|_g |_nd |_d S )NF)child   )dillZ_dillZis_dillisEnabledForloggingINFO_trace_depth_size_stack)r   picklerr   r   r   trace_setup   s    zTraceAdapter.trace_setupc           	   	   O   s(  t |ds tj|f|| d S |jd kr.d S |di }|d}d }zH|j }|jj	}z|| 7 }W n  t
k
r   |t|7 }Y nX W n t
tfk
r   Y nX |d k	r|s|j| n||j 8 }||d< |r| jd8  _|j|d< ||d< | j|f|| |s$| jd7  _d S )Nr$   extra#sizer   depth)hasattrr   infor$   get
startswith_filetellframercurrent_frameAttributeErrorlen	TypeErrorr%   appendpop)	r   r&   r   argsr   r(   Z
pushed_objr*   framer   r   r   r      s:    




zTraceAdapter.traceN)
__name__
__module____qualname____doc__r   r   r   r   r'   r   r   r   r   r   r   b   s   	r   c                       s2   e Zd ZdZdd fdd
Z fddZ  ZS )r   z
    Generates message prefix and suffix from record.

    This Formatter adds prefix and suffix strings to the log message in trace
    mode (an also provides empty string defaults for normal logs).
    Nr   c                   s   t  j|| z|jj}|d kr$tW n tk
rB   t }Y nX zt|j	}W n t
k
rn   d| _Y nX |tdj	k| _d S )NFzutf-8)superr   streamencodingr4   localegetpreferredencodingcodecslookupnameLookupErroris_utf8)r   r   r9   r   rA   	__class__r   r   r      s    zTraceFormatter.__init__c                    s   ddd}t |dddkr||jdr:|jd d d }n"|jdkrJd	}n|jd
 d d }| jsp|td }|d |d< t|drtt	
|jd
d }|j|d ? }d||rd| d ndf |d< t|| t |S )N )prefixsuffixr+   r   r)   r   r   r   r      u   ├┬- rL   r*   
   z	 [%d %sB]ZKMGTPirM   )getattrr   r/   r+   rH   	translate	ASCII_MAPr,   intmathlogr*   varsupdater?   format)r   recordfieldsrL   powerr*   rI   r   r   r[      s     


 zTraceFormatter.format)r;   r<   r=   r>   r   r[   __classcell__r   r   rI   r   r      s   r   r    Fa)mode)argra   returnc                C   s0   t | tst| |dS t| r$tjntj dS )u}  print a trace through the stack when pickling; useful for debugging

    With a single boolean argument, enable or disable the tracing.

    Example usage:

        >>> import dill
        >>> dill.detect.trace(True)
        >>> dill.dump_session()

    Alternatively, ``trace()`` can be used as a context manager. With no
    arguments, it just takes care of restoring the tracing state on exit.
    Either a file handle, or a file name and (optionally) a file mode may be
    specitfied to redirect the tracing output in the ``with`` block context. A
    log function is yielded by the manager so the user can write extra
    information to the file.

    Example usage:

        >>> from dill import detect
        >>> D = {'a': 42, 'b': {'x': None}}
        >>> with detect.trace():
        >>>     dumps(D)
        ┬ D2: <dict object at 0x7f2721804800>
        ├┬ D2: <dict object at 0x7f27217f5c40>
        │└ # D2 [8 B]
        └ # D2 [22 B]
        >>> squared = lambda x: x**2
        >>> with detect.trace('output.txt', mode='w') as log:
        >>>     log("> D = %r", D)
        >>>     dumps(D)
        >>>     log("> squared = %r", squared)
        >>>     dumps(squared)

    Arguments:
        arg: a boolean value, or an optional file-like or path-like object for the context manager
        mode: mode string for ``open()`` if a file name is passed as the first argument
    )filera   N)
isinstanceboolTraceManagerr   setLevelr"   r#   WARNING)rb   ra   r   r   r   r      s    '
c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	rg   zDcontext manager version of trace(); can redirect the trace to a filec                 C   s&   || _ || _|d k	| _t|d| _d S )Nwrite)rd   ra   redirectr,   file_is_stream)r   rd   ra   r   r   r   r     s    
zTraceManager.__init__c                 C   sh   | j rLt  | jr$t| j| _nt| j| j	| _t
t t
| j t
 | _t
tj t
jS r   )rk   stderr_handlerflushrl   r"   StreamHandlerrd   r   FileHandlerra   r   r   r   getEffectiveLevel	old_levelrh   r#   r-   )r   r   r   r   	__enter__  s    

zTraceManager.__enter__c                 G   s<   t | j | jr8t | j t t | js8| j	  d S r   )
r   rh   rr   rk   r   r   r   rm   rl   close)r   exc_infor   r   r   __exit__  s    
zTraceManager.__exit__N)r;   r<   r=   r>   r   rs   rv   r   r   r   r   rg     s   rg   )N)!r>   __all__rD   
contextlibrB   r"   rW   os	functoolsr   typingr   r   r    str	maketransrU   LoggerAdapterr   	Formatterr   	getLoggerr   	propagater   _StderrHandlerrm   r   rf   PathLiker   AbstractContextManagerrg   r   r   r   r   <module>   s(   $
(H)

(+