
    .Phwp                        d 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 ddl	m
Z
mZmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZmZm Z m!Z!  ed	 e                        ed
 e                        ed e                        ed e                        ed e                        ed e                       dZ" G d de#          Z$ G d de          Z% G d de          Z&ddZ'ddZ(d Z)ddZ*dS )zFUtilities for fast persistence of big data, with optional compression.    N)Path   )make_memmap)_COMPRESSORSLZ4_NOT_INSTALLED_ERRORBinaryZlibFileBZ2CompressorWrapperGzipCompressorWrapperLZ4CompressorWrapperLZMACompressorWrapperXZCompressorWrapperZlibCompressorWrapperlz4register_compressor)NDArrayWrapperZNDArrayWrapperload_compatibility)BUFFER_SIZEPickler	Unpickler_ensure_native_byte_order_read_bytes_reconstruct_validate_fileobject_and_memmap_write_fileobjectzlibgzipbz2lzmaxzr      c                   <    e Zd ZdZdefdZd Zd Zd Zd Z	d Z
d	S )
NumpyArrayWrapperap  An object to be persisted instead of numpy arrays.

    This object is used to hack into the pickle machinery and read numpy
    array data from our custom persistence format.
    More precisely, this object is used for:
    * carrying the information of the persisted array: subclass, shape, order,
    dtype. Those ndarray metadata are used to correctly reconstruct the array
    with low level numpy functions.
    * determining if memmap is allowed on the array.
    * reading the array bytes from a file.
    * reading the array using memorymap from a file.
    * writing the array bytes to a file.

    Attributes
    ----------
    subclass: numpy.ndarray subclass
        Determine the subclass of the wrapped array.
    shape: numpy.ndarray shape
        Determine the shape of the wrapped array.
    order: {'C', 'F'}
        Determine the order of wrapped array data. 'C' is for C order, 'F' is
        for fortran order.
    dtype: numpy.ndarray dtype
        Determine the data type of the wrapped array.
    allow_mmap: bool
        Determine if memory mapping is allowed on the wrapped array.
        Default: False.
    Fc                 Z    || _         || _        || _        || _        || _        || _        dS )z4Constructor. Store the useful information for later.N)subclassshapeorderdtype
allow_mmapnumpy_array_alignment_bytes)selfr%   r&   r'   r(   r)   r*   s          S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/numpy_pickle.py__init__zNumpyArrayWrapper.__init__^   s8     !


$ ,G(((    c                 $    t          | dd           S )Nr*   )getattr)r+   s    r,   $safe_get_numpy_array_alignment_bytesz6NumpyArrayWrapper.safe_get_numpy_array_alignment_bytesr   s     t:DAAAr.   c                 d   t          d|j        z  d          }|j        j        rt	          j        ||j        d           dS |                                 }||j                                        }|dz   }|||z  z
  }t          
                    |dd          }|j                            |           |dk    rd	|z  }	|j                            |	           |j                            |g d
|| j                  D ]/}
|j                            |
                    d                     0dS )zWrite array bytes to pickler file handle.

        This function is an adaptation of the numpy write_array function
        available in version 1.10.1 in numpy/lib/format.py.
        i   r      protocolNlittle)length	byteorderr      )external_loopbufferedzerosize_ok)flags
buffersizer'   C)maxitemsizer(   	hasobjectpickledumpfile_handler1   tellintto_byteswritenpnditerr'   tobytes)r+   arraypicklerr>   r*   current_pospos_after_padding_bytepadding_lengthpadding_length_bytepaddingchunks              r,   write_arrayzNumpyArrayWrapper.write_arrayw   sf    7;;
;  	> Kw2Q??????*.*S*S*U*U'*6%16688)4q&!<*-HH"
 '*ll"1 '3 ' '# #))*=>>>!Q&&%6G'--g666 **BBB%j	 +   > > #))%--*<*<====> >r.   c                    t          | j                  dk    rd}n2fd| j        D             }j        j                            |          }| j        j        rt          j        j	                  }ny| 
                                }|Vj	                            d          }t                              |d          }|dk    rj	                            |           t          t          t          | j        j                  z  }	j                            || j                  }t%          d||	          D ]r}
t          |	||
z
            }t          || j        j        z            }t'          j	        |d          }j                            || j        |	          ||
|
|z   <   ~s| j        d
k    r*| j        ddd         |_        |                                }n| j        |_        |rt/          |          }|S )zRead array from unpickler file handle.

        This function is an adaptation of the numpy read_array function
        available in version 1.10.1 in numpy/lib/format.py.
        r   r   c                 D    g | ]}j                             |          S  )rJ   int64).0x	unpicklers     r,   
<listcomp>z0NumpyArrayWrapper.read_array.<locals>.<listcomp>   s)    EEEQ9<--a00EEEr.   Nr6   r8   )r(   z
array data)r(   countF)lenr&   rJ   multiplyreducer(   rB   rC   loadrE   r1   readrG   
from_bytesr   minrA   emptyranger   
frombufferr'   	transposer   )r+   r\   ensure_native_byte_orderr_   shape_int64rM   r*   padding_byterQ   max_read_counti
read_count	read_sizedatas    `            r,   
read_arrayzNumpyArrayWrapper.read_array   s    tz??aEE FEEE$*EEEKL)00==E: "	)K	 566EE*.*S*S*U*U'*6(499!<<!$!Q!Q!Q&&)..~>>> )CTZ=P,Q,QQNL&&uDJ&??E1e^44   ;;

TZ-@ @AA	"9#8)\RR,5L,C,C
* -D - -a!j.() DzS  "j2.))"j# 	5-e44Er.   c                    |j                                         }|}|                                 }|>|j                             d          }t                              |d          }||dz   z  }|j        dk    rd|_        t          |j        | j	        | j
        | j        |j        |          }|j                             ||j        z              |5|t          z  dk    r'd	| d
|j         j         d}t!          j        |           |S )z!Read an array using numpy memmap.Nr   r6   r^   zw+zr+)r(   r&   r'   modeoffsetr   zThe memmapped array z loaded from the file a   is not byte aligned. This may cause segmentation faults if this memmapped array is used in some libraries like BLAS or PyTorch. To get rid of this warning, regenerate your pickle file with joblib >= 1.2.0. See https://github.com/joblib/joblib/issues/563 for more details)rE   rF   r1   rf   rG   rg   	mmap_moder   filenamer(   r&   r'   seeknbytesNUMPY_ARRAY_ALIGNMENT_BYTESnamewarningswarn)	r+   r\   rO   rx   r*   ro   rQ   marraymessages	            r,   	read_mmapzNumpyArrayWrapper.read_mmap   s3   +0022&*&O&O&Q&Q#&2$055a88L ^^LH^MMNnq((F$&&"&I***$
 
 
 	""6FM#9::: (/99Q>>#v # #(-# # #  M'"""r.   c                 F   |j         )| j        r"|r
J d            |                     |          }n|                     ||          }t	          |d          rJ| j        |j        j        |j        j        fvr+t          | j        dd          }|
                    |          S |S )a  Read the array corresponding to this wrapper.

        Use the unpickler to get all information to correctly read the array.

        Parameters
        ----------
        unpickler: NumpyUnpickler
        ensure_native_byte_order: bool
            If true, coerce the array to use the native endianness of the
            host system.

        Returns
        -------
        array: numpy.ndarray

        NzNMemmaps cannot be coerced to a given byte order, this code path is impossible.__array_prepare__)r   b)ry   r)   r   ru   hasattrr%   rJ   ndarraymemmapr   r   )r+   r\   rm   rM   	new_arrays        r,   rf   zNumpyArrayWrapper.read  s    $ *t*/  0   NN9--EEOOI/GHHE 5-.. 	4=L LI
 4
 4

 %T]D#>>I..u555Lr.   N)__name__
__module____qualname____doc__r}   r-   r1   rU   ru   r   rf   rX   r.   r,   r#   r#   @   s         F $?G G G G(B B B
&> &> &>P6 6 6p* * *X$ $ $ $ $r.   r#   c                   X    e Zd ZdZej                                        ZddZd Zd Z	dS )NumpyPicklera  A pickler to persist big data efficiently.

    The main features of this object are:
    * persistence of numpy arrays in a single file.
    * optional compression with a special care on avoiding memory copies.

    Attributes
    ----------
    fp: file
        File object handle used for serializing the input object.
    protocol: int, optional
        Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.
    Nc                     || _         t          | j         t                    | _        |t          j        }t          j        | | j         |           	 dd l}n# t          $ r d }Y nw xY w|| _
        d S )Nr4   r   )rE   
isinstancer   r;   rC   DEFAULT_PROTOCOLr   r-   numpyImportErrorrJ   )r+   fpr5   rJ   s       r,   r-   zNumpyPickler.__init__?  s    "4#3^DD .Ht/(CCCC	 	 	 	BBB	s   A A&%A&c                 &   |j         j        r|j         j        sdnd}| j         o|j        j         }i }	 | j                                         n# t          j	        $ r ddi}Y nw xY wt          t          |          |j        ||j        fd|i|}|S )z<Create and returns a numpy array wrapper from a numpy array.r`   r?   r*   Nr)   )r=   f_contiguousc_contiguousr;   r(   rB   rE   rF   ioUnsupportedOperationr#   typer&   )r+   rM   r'   r)   kwargswrappers         r,   _create_array_wrapperz"NumpyPickler._create_array_wrapperP  s     K,WU[5MWCCTW 	 &Du{/D+D
	;!!####& 	; 	; 	;3T:FFF	; $KKKK	
 

 "
 
 
 s   A A%$A%c                    | j         t          |          | j         j        | j         j        | j         j        fv rt          |          | j         j        u r| j                             |          }|                     |          }t          j        | |           | j	        dk    r| j
                            d           |                    ||            dS t          j        | |          S )a  Subclass the Pickler `save` method.

        This is a total abuse of the Pickler class in order to use the numpy
        persistence function `save` instead of the default pickle
        implementation. The numpy array is replaced by a custom wrapper in the
        pickle persistence stack and the serialized array is written right
        after in the file. Warning: the file produced does not follow the
        pickle format. As such it can not be read with `pickle.load`.
        N   T)force)rJ   r   r   matrixr   
asanyarrayr   r   saveprotoframercommit_framerU   )r+   objr   s      r,   r   zNumpyPickler.saveh  s     7499GOGNGN1
 $
 $

 CyyDGN**g((-- 0055GLw''' zQ((t(444 T***F|D#&&&r.   N)
r   r   r   r   r   dispatchcopyr-   r   r   rX   r.   r,   r   r   .  sf          $$&&H   "  0#' #' #' #' #'r.   r   c                   r    e Zd ZdZej                                        ZddZd Zeee	j
        d         <   dS )NumpyUnpickleraZ  A subclass of the Unpickler to unpickle our numpy pickles.

    Attributes
    ----------
    mmap_mode: str
        The memorymap mode to use for reading numpy arrays.
    file_handle: file_like
        File object to unpickle from.
    ensure_native_byte_order: bool
        If True, coerce the array to use the native endianness of the
        host system.
    filename: str
        Name of the file to unpickle from. It should correspond to file_handle.
        This parameter is required when using mmap_mode.
    np: module
        Reference to numpy module if numpy is installed else None.

    Nc                    t           j                            |          | _        || _        || _        || _        d| _        || _        t          j
        | | j                   	 dd l}n# t          $ r d }Y nw xY w|| _        d S )NFr   )ospathdirname_dirnamery   rE   rz   compat_moderm   r   r-   r   r   rJ   )r+   rz   rE   rm   ry   rJ   s         r,   r-   zNumpyUnpickler.__init__  s     11"&  (@%4!1222	 	 	 	BBB	s   #A( (A76A7c                    t          j        |            t          | j        d         t          t
          f          r| j        t          d          | j                                        }t          |t                    rd| _	        |
                    |           }n|
                    | | j                  }| j                            |           dS dS )aO  Called to set the state of a newly created object.

        We capture it to replace our place-holder objects, NDArrayWrapper or
        NumpyArrayWrapper, by the array we are interested in. We
        replace them directly in the stack of pickler.
        NDArrayWrapper is used for backward compatibility with joblib <= 0.9.
        ra   Nz@Trying to unpickle an ndarray, but numpy didn't import correctlyT)r   
load_buildr   stackr   r#   rJ   r   popr   rf   rm   append)r+   array_wrapper_array_payloads      r,   r   zNumpyUnpickler.load_build  s     	T""" djn~7H&IJJ 	.w!V   !JNN,,M -88 Y#' !.!3!3D!9!9!.!3!3D$:W!X!XJn-----	. 	.r.   r   r   )r   r   r   r   r   r   r   r-   r   rC   BUILDrX   r.   r,   r   r     se         & !&&((H   $. . .: !+HV\!_r.   r   c           
         t           $t          |t                     rt          |          }t          |t                    }t          |d          }d}|du rd}npt          |t                    r;t          |          dk    r"t          d                    |                    |\  }}n t          |t                    r	|}d}||f}n|}|dk    rt          t          t                    |R|durN|t          d	          vr=t          d
                    |t          t          d	                                        |t          vr(t          d                    |t                              |s%|s#t          d|dt          |          d          |r]t          |t                    sHd}t          j                    D ]!\  }}	|                    |	j                  r|}"|t          v r|dk    rd}|dk    rPt#          |||f          5 }
t%          |
|                              |            ddd           n# 1 swxY w Y   ns|rMt)          |d          5 }
t%          |
|                              |            ddd           n# 1 swxY w Y   n$t%          ||                              |            |rdS |gS )a  Persist an arbitrary Python object into one file.

    Read more in the :ref:`User Guide <persistence>`.

    Parameters
    ----------
    value: any Python object
        The object to store to disk.
    filename: str, pathlib.Path, or file object.
        The file object or path of the file in which it is to be stored.
        The compression method corresponding to one of the supported filename
        extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used
        automatically.
    compress: int from 0 to 9 or bool or 2-tuple, optional
        Optional compression level for the data. 0 or False is no compression.
        Higher value means more compression, but also slower read and
        write times. Using a value of 3 is often a good compromise.
        See the notes for more details.
        If compress is True, the compression level used is 3.
        If compress is a 2-tuple, the first element must correspond to a string
        between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'
        'xz'), the second element must be an integer from 0 to 9, corresponding
        to the compression level.
    protocol: int, optional
        Pickle protocol, see pickle.dump documentation for more details.

    Returns
    -------
    filenames: list of strings
        The list of file names in which the data is stored. If
        compress is false, each array is stored in a different file.

    See Also
    --------
    joblib.load : corresponding loader

    Notes
    -----
    Memmapping on load cannot be used for compressed files. Thus
    using compression can significantly slow down loading. In
    addition, compressed files take up extra memory during
    dump and load.

    NrI   r   T   zkCompress argument tuple should contain exactly 2 elements: (compress method, compress level), you passed {}r   F
   z=Non valid compress level given: "{}". Possible values are {}.zANon valid compression method given: "{}". Possible values are {}.z<Second argument should be a filename or a file-like object, z (type z) was given.r   )compressr4   wb)r   r   strr   tuplerb   
ValueErrorformatr   r   rj   listr   r   itemsendswith	extensionr   r   rD   open)valuerz   r   r5   is_filename
is_fileobjcompress_methodcompress_levelr~   
compressorfs              r,   rD   rD     s   \ Jx66x==Xs++K7++JO4 	He	$	$ "x==ACCI6(CSCS   +3'	Hc	"	" ""#^4!%CK0111 	"%''%))++ KRRU2YY 
 
 	
 l**OVV 
 
 	
  
z 
 j)14>>>>C
 
 	

  ":h66 "  , 2 4 4 	' 	'D*  !566 '"&l**~/B/B "N@
 
 
 	;X...33E:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 
 >(D!! 	;QX...33E:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	X11166u===   :s$   %I  II%JJJ c                     t          || ||          }d}	 |                                }|j        rt          j        d|z  t
          d           n*# t          $ r}t          d          }||_        |d}~ww xY w|S )zInternal unpickling function.)ry   NzjThe file '%s' has been generated with a joblib version less than 0.10. Please regenerate this pickle file.   )
stacklevelzyYou may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.)	r   re   r   r   r   DeprecationWarningUnicodeDecodeErrorr   	__cause__)fobjrm   rz   ry   r\   r   excnew_excs           r,   	_unpickler   e  s     $0I  I Cnn  	M68@A #       7
 

   Js   :A 
A9A44A9c                 2   ddl m}m} t          | d          5 }t	          || |          5 \  }}t          |d| |          }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   |                    |j                   |r ||           |S )Nr   )JOBLIB_MMAPSadd_maybe_unlink_finalizerrbFrm   rz   ry   )_memmapping_reducerr   r   r   r   r   addrz   )	rz   ry   unlink_on_gc_collectr   r   r   r   validated_mmap_moder   s	            r,   load_temporary_memmapr     sB   MMMMMMMM	h		 ,Q)DD 	 I
 ).!-	  C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	              $ S\""" (""3'''Js4   A%AA%A	A%A	A%%A),A)autoc                    |dk    r|du }|r|t          d| d          t          $t          | t                    rt          |           } t	          | d          rQ| }t          |dd          } t          || |          5 \  }}t          ||          }ddd           n# 1 swxY w Y   nt          | d	          5 }t          || |          5 \  }}t          |t                    r't          |          cddd           cddd           S t          ||| |
          }ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |S )a  Reconstruct a Python object from a file persisted with joblib.dump.

    Read more in the :ref:`User Guide <persistence>`.

    WARNING: joblib.load relies on the pickle module and can therefore
    execute arbitrary Python code. It should therefore never be used
    to load files from untrusted sources.

    Parameters
    ----------
    filename: str, pathlib.Path, or file object.
        The file object or path of the file from which to load the object
    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
        If not None, the arrays are memory-mapped from the disk. This
        mode has no effect for compressed files. Note that in this
        case the reconstructed object might no longer match exactly
        the originally pickled object.
    ensure_native_byte_order: bool, or 'auto', default=='auto'
        If True, ensures that the byte order of the loaded arrays matches the
        native byte ordering (or _endianness_) of the host system. This is not
        compatible with memory-mapped arrays and using non-null `mmap_mode`
        parameter at the same time will raise an error. The default 'auto'
        parameter is equivalent to True if `mmap_mode` is None, else False.

    Returns
    -------
    result: any Python object
        The object stored in the file.

    See Also
    --------
    joblib.dump : function to save an object

    Notes
    -----

    This function can load numpy array files saved separately during the
    dump. If the mmap_mode argument is given, it is passed to np.load and
    arrays are loaded as memmaps. As a consequence, the reconstructed
    object might not match the original pickled object. Note that if the
    file was saved with compression, the arrays cannot be memmapped.
    r   NzfNative byte ordering can only be enforced if 'mmap_mode' parameter is set to None, but got 'mmap_mode=z
' instead.rf   r~   r   )rm   r   r   )
r   r   r   r   r   r0   r   r   r   r   )rz   ry   rm   r   _r   r   r   s           r,   re   re     s   V  6))#,#4  
I$9H2;H H H
 
 	

 Jx66x==x   4,,,T8YGG 	U9DRSD;STTTC	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U (D!! 	Q0HiHH  M#dC(( 4 .d33      	 	 	 	 	 	 	 	  -E%1	                	 	 	 	 	 	 	 	 	 	 	 	 	 	 	* JsT   B""B&)B&>E'D/7ED/#E/D3	3E6D3	7EE
E
)r   N)r   N)Nr   )+r   r   r   rC   r   pathlibr   	backportsr   r   r   r   r   r	   r
   r   r   r   r   r   r   numpy_pickle_compatr   r   r   numpy_pickle_utilsr   r   r   r   r   r   r   r   r}   objectr#   r   r   rD   r   r   re   rX   r.   r,   <module>r      s   L L 
			 				         " " " " " "                                   
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  F1133 4 4 4  F1133 4 4 4  E//11 2 2 2  F1133 4 4 4  D--// 0 0 0  E//11 2 2 2 ! g g g g g g g g\]' ]' ]' ]' ]'7 ]' ]' ]'@E+ E+ E+ E+ E+Y E+ E+ E+XH H H HV   D  6R R R R R Rr.   