
    &`iB                        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Z d dlmZmZmZmZmZmZ d dlZd dlmZ d dlmZmZ d dlmZ  ej        e          ZdZdZ  G d	 d
e!          Z" ed           G d de"                      Z#dde$de$de$fdZ%de$dee$         fdZ&de$fdZ'de$fdZ(de$fdZ)dS )    N)Path)AnyDictIteratorListOptionalUnion)TempFileLock)_download_from_fs_path_exists_at_fs_path)	PublicAPIz.metadata.jsoncheckpoint_tmp_c                        e Zd Z fdZ xZS )_CheckpointMetaClassc                     	 t                                          |          S # t          $ rC}|dv rt          |          ||dv rt	          |          ||dv rt          |          ||d }~ww xY w)N>   to_dictto_bytes	from_dict
from_bytesget_internal_representation>   urito_urifrom_uri>   get_preprocessorset_preprocessor)super__getattribute__AttributeError_get_migration_error_get_uri_error_get_preprocessor_error)selfitemexc	__class__s      i/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/_checkpoint.py__getattr__z _CheckpointMetaClass.__getattr__   s    	77++D111 	 	 	    +400c9   
 %T**3AAA-d33<I%	s    $ 
A1>A,,A1)__name__
__module____qualname__r'   __classcell__)r%   s   @r&   r   r      s8                    r   beta)	stabilityc                   d   e Zd ZdZ	 ddeeej        f         ded         fdZ	d Z
deeef         fd	Zd
eeef         ddfdZd
eeef         ddfdZedeeej        f         dd fd            Zddeeeej        f                  defdZej        dee         fd            ZdefdZd ZdS )
Checkpointa  A reference to data persisted as a directory in local or remote storage.

    Access the checkpoint contents locally using ``checkpoint.to_directory()``
    or ``checkpoint.as_directory``.

    Attributes
    ----------
    path: A path on the filesystem containing the checkpoint contents.
    filesystem: PyArrow FileSystem that can be used to access data at the `path`.

    See Also
    --------
    ray.train.report : Report a checkpoint during training (with Ray Train/Tune).
    ray.train.get_checkpoint : Get the latest checkpoint during training
        (for restoration).

    :ref:`train-checkpointing`
    :ref:`persistent-storage-guide`

    Examples
    --------

    Creating a checkpoint using ``Checkpoint.from_directory``:

        >>> from ray.train import Checkpoint
        >>> checkpoint = Checkpoint.from_directory("/tmp/example_checkpoint_dir")
        >>> checkpoint.filesystem  # doctest: +ELLIPSIS
        <pyarrow._fs.LocalFileSystem object...
        >>> checkpoint.path
        '/tmp/example_checkpoint_dir'

    Creating a checkpoint from a remote URI:

        >>> checkpoint = Checkpoint("s3://bucket/path/to/checkpoint")
        >>> checkpoint.filesystem  # doctest: +ELLIPSIS
        <pyarrow._s3fs.S3FileSystem object...
        >>> checkpoint.path
        'bucket/path/to/checkpoint'

    Creating a checkpoint with a custom filesystem:

        >>> checkpoint = Checkpoint(
        ...     path="bucket/path/to/checkpoint",
        ...     filesystem=pyarrow.fs.S3FileSystem(),
        ... )
        >>> checkpoint.filesystem  # doctest: +ELLIPSIS
        <pyarrow._s3fs.S3FileSystem object...
        >>> checkpoint.path
        'bucket/path/to/checkpoint'

    Accessing a checkpoint's contents:

        >>> import os  # doctest: +SKIP
        >>> with checkpoint.as_directory() as local_checkpoint_dir:  # doctest: +SKIP
        ...    print(os.listdir(local_checkpoint_dir))  # doctest: +SKIP
        ['model.pt', 'optimizer.pt', 'misc.pt']
    Npath
filesystemzpyarrow.fs.FileSystemc                     t          |          | _        || _        |r3|s1t          j        j                            |          \  | _        | _        t          j                    | _	        dS )a  Construct a Checkpoint.

        Args:
            path: A local path or remote URI containing the checkpoint data.
                If a filesystem is provided, then this path must NOT be a URI.
                It should be a path on the filesystem with the prefix already stripped.
            filesystem: PyArrow FileSystem to use to access data at the path.
                If not specified, this is inferred from the URI scheme.
        N)
strr1   r2   pyarrowfs
FileSystemr   uuiduuid4_uuid)r"   r1   r2   s      r&   __init__zCheckpoint.__init__s   s]     II	$ 	N
 	N)0)>)G)G)M)M&DOTY Z\\


r,   c                 2    d| j         j         d| j         dS )NzCheckpoint(filesystem=z, path=))r2   	type_namer1   r"   s    r&   __repr__zCheckpoint.__repr__   s"    V(AVV$)VVVVr,   returnc                 b   t          | j        t                                                    }t	          | j        |          si S | j                            |          5 }t          j        |	                                
                    d                    cddd           S # 1 swxY w Y   dS )z{Return the metadata dict stored with the checkpoint.

        If no metadata is stored, an empty dict is returned.
        utf-8N)r   r1   _METADATA_FILE_NAMEas_posixr   r2   open_input_filejsonloadsreadalldecode)r"   metadata_pathfs      r&   get_metadatazCheckpoint.get_metadata   s    
 TY(;<<EEGG!$/=AA 	I_,,];; 	;q:aiikk0099::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;s   9B$$B(+B(metadatac                 8   t          | j        t                                                    }| j                            |          5 }|                    t          j        |          	                    d                     ddd           dS # 1 swxY w Y   dS )zSet the metadata stored with this checkpoint.

        This will overwrite any existing metadata stored with this checkpoint.
        rC   N)
r   r1   rD   rE   r2   open_output_streamwriterG   dumpsencode)r"   rN   rK   rL   s       r&   set_metadatazCheckpoint.set_metadata   s    
 TY(;<<EEGG_//>> 	:!GGDJx((//88999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:s   ;BBBc                     |                                  }|                    |           |                     |           dS )zUpdate the metadata stored with this checkpoint.

        This will update any existing metadata stored with this checkpoint.
        N)rM   updaterT   )r"   rN   existing_metadatas      r&   update_metadatazCheckpoint.update_metadata   sE    
 !--//  ***+,,,,,r,   c                 T     | |t           j                                                  S )zCreate checkpoint object from a local directory.

        Args:
            path: Local directory containing checkpoint data.

        Returns:
            A ray.train.Checkpoint object.
        )r2   )r5   r6   LocalFileSystem)clsr1   s     r&   from_directoryzCheckpoint.from_directory   s'     s4GJ$>$>$@$@AAAAr,   c                 b   |du}|r|n|                                  }t          j                            t          j                            t          |                              }t          j        |d           	 t          |d          5  t          | j	        | j        |           ddd           n# 1 swxY w Y   nl# t          $ r_ t          |d          5  	 ddd           n# 1 swxY w Y   t          j                            |          st          d| d	          Y nw xY w|S )
a9  Write checkpoint data to a local directory.

        *If multiple processes on the same node call this method simultaneously,*
        only a single process will perform the download, while the others
        wait for the download to finish. Once the download finishes, all processes
        receive the same local directory to read from.

        Args:
            path: Target directory to download data to. If not specified,
                this method will use a temporary directory.

        Returns:
            str: Directory containing checkpoint data.
        NT)exist_okr   timeout)r6   fs_path
local_pathzCheckpoint directory z does not exist, even though it should have been created by another process. Please raise an issue on GitHub: https://github.com/ray-project/ray/issues)_get_temporary_checkpoint_dirosr1   normpath
expanduserr4   makedirsr
   r   r2   TimeoutErrorexistsRuntimeError)r"   r1   user_provided_pathrb   s       r&   to_directoryzCheckpoint.to_directory   s    "-&PDDD,N,N,P,P 	 W%%bg&8&8Z&I&IJJ

J....	 j!444  &	j                   
	 
	 
	j"555                7>>*-- "@J @ @ @   	
	 sZ   =C B7+C 7B;;C >B;?C D,C, D,,C0	0D,3C0	45D,+D,c           
   #     K   t          | j        t          j        j                  r| j        V  dS t          |                                           }t          |d          	                                 | 
                                }	 |V  	 t          j        |           nA# t          $ r4 t                              d| dt!          j                                Y nw xY wt%          |          }|sT	 t'          |d          5  t)          j        |d           ddd           dS # 1 swxY w Y   dS # t,          $ r Y dS w xY wdS # 	 t          j        |           nA# t          $ r4 t                              d| dt!          j                                Y nw xY wt%          |          }|sQ	 t'          |d          5  t)          j        |d           ddd           w # 1 swxY w Y   w # t,          $ r Y w w xY ww xY w)	aE  Returns checkpoint contents in a local directory as a context.

        This function makes checkpoint data available as a directory while avoiding
        unnecessary copies and left-over temporary data.

        *If the checkpoint points to a local directory*, this method just returns the
        local directory path without making a copy, and nothing will be cleaned up
        after exiting the context.

        *If the checkpoint points to a remote directory*, this method will download the
        checkpoint to a local temporary directory and return the path
        to the temporary directory.

        *If multiple processes on the same node call this method simultaneously,*
        only a single process will perform the download, while the others
        wait for the download to finish. Once the download finishes, all processes
        receive the same local (temporary) directory to read from.

        Once all processes have finished working with the checkpoint,
        the temporary directory is cleaned up.

        Users should treat the returned checkpoint directory as read-only and avoid
        changing any data within it, as it may be deleted when exiting the context.

        Example:

        .. testcode::
            :hide:

            from pathlib import Path
            import tempfile

            from ray.train import Checkpoint

            temp_dir = tempfile.mkdtemp()
            (Path(temp_dir) / "example.txt").write_text("example checkpoint data")
            checkpoint = Checkpoint.from_directory(temp_dir)

        .. testcode::

            with checkpoint.as_directory() as checkpoint_dir:
                # Do some read-only processing of files within checkpoint_dir
                pass

            # At this point, if a temporary directory was created, it will have
            # been deleted.

        azCould not remove z  deletion file lock. Traceback:
r   r_   T)ignore_errorsN)
isinstancer2   r5   r6   rZ   r1   _get_del_lock_pathrd   opencloserm   re   remove	Exceptionloggerwarning	traceback
format_exc_list_existing_del_locksr
   shutilrmtreeri   )r"   del_lock_pathtemp_dirremaining_lockss       r&   as_directoryzCheckpoint.as_directory   sH     d dowz'ABB $	)OOOOO.t/Q/Q/S/STTM$$**,,,((**H
Im,,,,    NN@M @ @'0';'='=@ @     #;8"D"D&  *(A>>> H H"M($GGGGH H H H H H H H H H H H H H H H H H'    Im,,,,    NN@M @ @'0';'='=@ @     #;8"D"D&  *(A>>> H H"M($GGGGH H H H H H H H H H H H H H H H'   s   
E B$ $;C"!C"7D9 D,D9 ,D00D9 3D04D9 9
EEHE#"H#;F!H F!!H6G6G*G6)H*G..G61G.2G65H6
H HHHc                    t          j                    }t          | j        j        z   }t          j                    dk    rt          d          }t          | j        j        dt          t                    z   t          |          z   t          |          z   d         z   }|	                    t                    st          d          t          ||                                          S )zReturn the name for the temporary checkpoint dir that this checkpoint
        will get downloaded to, if accessing via `to_directory` or `as_directory`.
        Windows iNziCouldn't create checkpoint directory due to length constraints. Try specifying a shorter checkpoint path.)tempfile
gettempdir_CHECKPOINT_TEMP_DIR_PREFIXr:   hexplatformsystemrr   len
startswithrk   r   rE   )r"   tmp_dir_pathcheckpoint_dir_namedel_lock_names       r&   rd   z(Checkpoint._get_temporary_checkpoint_dirA  s      *,,9DJNJ?	)) /r22M+*.5667,''( -(() + +   '112MNN "M   L"566??AAAr,   c                      t          d          )Nz~You cannot use `Checkpoint` objects directly as paths. Use `Checkpoint.to_directory()` or `Checkpoint.as_directory()` instead.)	TypeErrorr?   s    r&   
__fspath__zCheckpoint.__fspath__[  s    V
 
 	
r,   N)r(   r)   r*   __doc__r	   r4   re   PathLiker   r;   r@   r   r   rM   rT   rX   classmethodr\   rm   
contextlibcontextmanagerr   r   rd   r    r,   r&   r0   r0   7   s       8 8z 9=" "C$%" 45" " " "<W W W
;d38n 
; 
; 
; 
;:T#s(^ : : : : :-S#X -4 - - - - 	B%R[(8"9 	Bl 	B 	B 	B [	B) )%R[0@*A!B )c ) ) ) )V Uhsm U U U UnBs B B B B4
 
 
 
 
r,   r0   )	metaclassr1   suffixrA   c                 ~    ||nt          t          j                              }|                     d           d| S )a  Get the path to the deletion lock file for a file/directory at `path`.

    Example:

        >>> _get_del_lock_path("/tmp/checkpoint_tmp")  # doctest: +ELLIPSIS
        '/tmp/checkpoint_tmp.del_lock_...
        >>> _get_del_lock_path("/tmp/checkpoint_tmp/")  # doctest: +ELLIPSIS
        '/tmp/checkpoint_tmp.del_lock_...
        >>> _get_del_lock_path("/tmp/checkpoint_tmp.txt")  # doctest: +ELLIPSIS
        '/tmp/checkpoint_tmp.txt.del_lock_...

    N/z
.del_lock_)r4   re   getpidrstrip)r1   r   s     r&   rr   rr   b  s@     )VVs29;;/?/?Fkk#22&222r,   c                 d    t          t          j        t          | d                               S )zList all the deletion lock files for a file/directory at `path`.

    For example, if 2 checkpoints are being read via `as_directory`,
    then this should return a list of 2 deletion lock files.
    *)r   )listglobrr   )r1   s    r&   r{   r{   s  s-     	/SAAACDDEEEr,   namec                 (    t          d|  d          S )N7The new `ray.train.Checkpoint` class does not support `a  ()`. Instead, only directories are supported.

Example to store a dictionary in a checkpoint:

import os, tempfile
import ray.cloudpickle as pickle
from ray import train
from ray.train import Checkpoint

with tempfile.TemporaryDirectory() as checkpoint_dir:
  with open(os.path.join(checkpoint_dir, 'data.pkl'), 'wb') as fp:
    pickle.dump({'data': 'value'}, fp)

  checkpoint = Checkpoint.from_directory(checkpoint_dir)
  train.report(..., checkpoint=checkpoint)

Example to load a dictionary from a checkpoint:

if train.get_checkpoint():
  with train.get_checkpoint().as_directory() as checkpoint_dir:
    with open(os.path.join(checkpoint_dir, 'data.pkl'), 'rb') as fp:
      data = pickle.load(fp)r   r   s    r&   r   r   |  s*    	($ 	( 	( 	(  r,   c                 (    t          d|  d          S )Nr   al  ()`. To create a checkpoint from remote storage, create a `Checkpoint` using its constructor instead of `from_directory`.
Example: `Checkpoint(path="s3://a/b/c")`.
Then, access the contents of the checkpoint with `checkpoint.as_directory()` / `checkpoint.to_directory()`.
To upload data to remote storage, use e.g. `pyarrow.fs.FileSystem` or your client of choice.r   r   s    r&   r    r      s*    	%$ 	% 	% 	%	 	 	r,   c                 (    t          d|  d          S )Nr   af  ()`. To include preprocessor information in checkpoints, pass it as metadata in the <Framework>Trainer constructor.
Example: `TorchTrainer(..., metadata={...})`.
After training, access it in the checkpoint via `checkpoint.get_metadata()`. See here: https://docs.ray.io/en/master/train/user-guides/data-loading-preprocessing.html#preprocessing-structured-datar   r   s    r&   r!   r!     s.    	I$ 	I 	I 	I  r,   r   )*r   r   rG   loggingre   r   r|   r   ry   r8   pathlibr   typingr   r   r   r   r   r	   
pyarrow.fsr5   ray.air._internal.filelockr
   ray.train._internal.storager   r   ray.util.annotationsr   	getLoggerr(   rw   rD   r   typer   r0   r4   rr   r{   r   r    r!   r   r,   r&   <module>r      sD          				               = = = = = = = = = = = = = = = =     3 3 3 3 3 3 R R R R R R R R * * * * * *		8	$	$ '  0     4   2 Vg
 g
 g
 g
 g
/ g
 g
 g
 g
T	3 3S 3# 3 3 3 3 3"F3 F49 F F F Fs    ,
 
 
 
 
	# 	 	 	 	 	 	r,   