
    &`io+                        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 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 d dlmZ  ej        e          Ze ed	           G d
 d                                  ZdS )    N)	dataclass)Path)AnyDictListOptionalTupleUnionunflattened_lookup)EXPR_ERROR_PICKLE_FILEEXPR_PROGRESS_FILEEXPR_RESULT_FILE)	PublicAPIstable	stabilityc                   j   e Zd ZU dZeeeef                  ed<   ed         ed<   ee	         ed<   eed<   dZ
ed         ed	<   dZeeedeeef         f                           ed
<   dZeej        j                 ed<   g dZedeeeef                  fd            Zedej        j        fd            ZddedefdZdefdZedej        j        dedefd            Ze	 ddeeej        f         deej        j                 dd fd            Z e d          dededed         fd            Z!dS )Resulta{  The final result of a ML training run or a Tune trial.

    This is the output produced by ``Trainer.fit``.
    ``Tuner.fit`` outputs a :class:`~ray.tune.ResultGrid` that is a collection
    of ``Result`` objects.

    This API is the recommended way to access the outputs such as:
    - checkpoints (``Result.checkpoint``)
    - the history of reported metrics (``Result.metrics_dataframe``, ``Result.metrics``)
    - errors encountered during a training run (``Result.error``)

    The constructor is a private API -- use ``Result.from_path`` to create a result
    object from a directory.

    Attributes:
        metrics: The latest set of reported metrics.
        checkpoint: The latest checkpoint.
        error: The execution error of the Trainable run, if the trial finishes in error.
        path: Path pointing to the result directory on persistent storage. This can
            point to a remote storage location (e.g. S3) or to a local location (path
            on the head node). The path is accessible via the result's associated
            `filesystem`. For instance, for a result stored in S3 at
            ``s3://bucket/location``, ``path`` will have the value ``bucket/location``.
        metrics_dataframe: The full result dataframe of the Trainable.
            The dataframe is indexed by iterations and contains reported
            metrics. Note that the dataframe columns are indexed with the
            *flattened* keys of reported metrics, so the format of this dataframe
            may be slightly different than ``Result.metrics``, which is an unflattened
            dict of the latest set of reported metrics.
        best_checkpoints: A list of tuples of the best checkpoints and
            their associated metrics. The number of
            saved checkpoints is determined by :class:`~ray.train.CheckpointConfig`
            (by default, all checkpoints will be saved).
    metricszray.tune.Checkpoint
checkpointerrorpathNzpd.DataFramemetrics_dataframebest_checkpoints_storage_filesystem)r   r   r   
filesystemr   returnc                 J    | j         sdS | j                             dd          S )z&The config associated with the result.Nconfig)r   getselfs    b/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/air/result.pyr    zResult.configI   s+     | 	4|$///    c                 L    | j         pt          j                                        S )zReturn the filesystem that can be used to access the result path.

        Returns:
            pyarrow.fs.FileSystem implementation.
        )r   pyarrowfsLocalFileSystemr"   s    r$   r   zResult.filesystemP   s      'G7:+E+E+G+GGr%   r   indentc                 T   	 ddl m} ddlm}  fd j        D             } j        rt           j                  j        |d<   n|                    d           |d         j	        |d<    j
        rLt          |                              |           fd j
                                        D             |d<   d	|z  }d	|d
z   z  		fd|                                D             }d                    |          }d                    |t                     j        |          S )zCConstruct the representation with specified number of space indent.r   )BLACKLISTED_KEYS)AUTO_RESULT_KEYSc                 2    i | ]}|t          |          S  )getattr).0kr#   s     r$   
<dictcomp>z Result._repr.<locals>.<dictcomp>^   s%    MMMAAwtQ//MMMr%   r   r   c                 $    i | ]\  }}|v	||S r/   r/   )r1   r2   vexcludes      r$   r3   z Result._repr.<locals>.<dictcomp>i   s0     + + +A'9I9I19I9I9Ir%   r       c                 (    g | ]\  }} | d |S )=r/   )r1   keyvalue
kws_indents      r$   
<listcomp>z Result._repr.<locals>.<listcomp>p   s=     
 
 
/9sEz*3****
 
 
r%   z,
z{0}{1}(
{2}
{0}))ray.tune.experimental.outputr,   ray.tune.resultr-   _items_to_reprr   type__name__pop	type_namer   setupdateitemsjoinformat)
r#   r*   r,   r-   shown_attributes
cls_indentkwskws_reprr6   r=   s
   `       @@r$   _reprzResult._reprY   sx   AAAAAA444444MMMM9LMMM: 	*(,TZ(8(8(AW%%  ))))9,)G)Q&< 	*++GNN+,,,+ + + +!%!3!3!5!5+ + +Y' 6\
FQJ'

 
 
 
=M=S=S=U=U
 
 
 ::c??#**:tDzz7JHUUUr%   c                 .    |                      d          S )Nr   )r*   )rO   r"   s    r$   __repr__zResult.__repr__v   s    zzz###r%   storage_filesystemstorage_pathc                     |                      |          5 }|                                                                cddd           S # 1 swxY w Y   dS )a   Opens a file as an input stream reading all byte content sequentially and
         decoding read bytes as utf-8 string.

        Args:
            storage_filesystem: The filesystem to use.
            storage_path: The source to open for reading.
        N)open_input_streamreadalldecode)rR   rS   fs      r$   _read_file_as_strzResult._read_file_as_stry   s      11,?? 	(199;;%%''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   &A		AAc           	         ddl m ddlm}m}m} ddlm}  |||          \   |          st          d d          t          t                                                    }t          t                                                    } ||          rX|                     |                              d          }	d |	D             }
t          j        |
d	
          }|
r|
d         ni }n ||          rct          j        t%          j        |                     |                              }|j        s|j        d                                         ni }n t          dt           dt           d          t/           |d                     }|rfd|D             }g }|D ]t}|||         |k             }|j        rt0                              d| d           |                    |j        ri n|j        d                                                    u|d         }t7          t9          ||                    }ndx}}d}t          t:                                                    } ||          rL                    |          5 }t>          j         !                    |          }ddd           n# 1 swxY w Y   tE          |||||          S )a3  Restore a Result object from local or remote trial directory.

        Args:
            path: A path of a trial directory on local or remote storage
                (ex: s3://bucket/path or /tmp/ray_results).
            storage_filesystem: A custom filesystem to use. If not provided,
                this will be auto-resolved by pyarrow. If provided, the path
                is assumed to be prefix-stripped already, and must be a valid path
                on the filesystem.

        Returns:
            A :py:class:`Result` object of that trial.
        r   )
Checkpoint)_exists_at_fs_path_list_at_fs_pathget_fs_and_path)CHECKPOINT_DIR_NAMEzTrial folder z doesn't exist!
c                 :    g | ]}|t          j        |          S r/   )jsonloads)r1   lines     r$   r>   z$Result.from_path.<locals>.<listcomp>   s'    DDDdtDD))DDDr%   /)sepz-Failed to restore the Result object: Neither z nor z exists in the trial folder!c                 t    | j         t          j        j        j        k    o| j                            d          S )Ncheckpoint_)rB   r'   r(   FileType	Directory	base_name
startswith)	file_infos    r$   <lambda>z"Result.from_path.<locals>.<lambda>   s5    in:&0/1 /B'22=AA r%   )file_filterc                 j    g | ]/} t          |                                                     0S ))r   r   )r   as_posix)r1   checkpoint_dir_namer[   r(   fs_paths     r$   r>   z$Result.from_path.<locals>.<listcomp>   sY        ( 
g':;;DDFFSU    r%   z(Could not find metrics corresponding to z&. These will default to an empty dict.N)r   r   r   r   r   r   r   )#	ray.trainr[   ray.train._internal.storager\   r]   r^   ray.train.constantsr_   RuntimeErrorr   r   rr   r   rY   splitpdjson_normalizeread_csvioStringIOemptyilocto_dictsortedloggerwarningappendlistzipr   rU   raycloudpickleloadr   )clsr   rR   r\   r]   r^   r_   result_json_fileprogress_csv_filelines	json_list
metrics_dflatest_metricscheckpoint_dir_namescheckpointsr   rs   #metrics_corresponding_to_checkpointlatest_checkpointr   r   error_file_pathrX   r[   r(   rt   s                          @@@r$   	from_pathzResult.from_path   sH   ( 	)(((((	
 	
 	
 	
 	
 	
 	
 	
 	
 	

 	<;;;;;%od,>??G!!"g.. 	IGwGGGHHH  )9::CCEE *<==FFHHb"233 	))".>??EEdKKEDDeDDDI*9#>>>J.7?Yr]]RNN$566 	C11"6GHHII J 6@5EM
#++---2 N I@P I I*I I I    &B B   
  
   	8      ,@	  K G';  #6@237JJ73 7< NNW.W W W   :@PBB<A"EMMOO    !,B  $CW$=$=>>3770 w(>??HHJJb/22 	0%%o66 0!,,Q//0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "( "(-
 
 
 	
s   $ KKKalphar   metricmodec                 6   | j         st          d          |dvrt          d| d          |dk    rt          nt          }fd| j         D             }|s-t          d d| j                                         d	           ||fd
          d         S )a  Get the best checkpoint from this trial based on a specific metric.

        Any checkpoints without an associated metric value will be filtered out.

        Args:
            metric: The key for checkpoints to order on.
            mode: One of ["min", "max"].

        Returns:
            :class:`Checkpoint <ray.train.Checkpoint>` object, or None if there is
            no valid checkpoint associated with the metric.
        z,No checkpoint exists in the trial directory!)maxminzUnsupported mode: z$. Please choose from ["min", "max"]!r   c                 D    g | ]}t          |d          d          |S )   N)defaultr   )r1   	ckpt_infor   s     r$   r>   z.Result.get_best_checkpoint.<locals>.<listcomp>  s<     
 
 
!&)A,EEEQ QQQr%   zInvalid metric name z-! You may choose from the following metrics: .c                 0    t          | d                   S )Nr   r   )xr   s    r$   ro   z,Result.get_best_checkpoint.<locals>.<lambda>  s    3EfaPQd3S3S r%   )r;   r   )r   rx   
ValueErrorr   r   r   keys)r#   r   r   opvalid_checkpointss    `   r$   get_best_checkpointzResult.get_best_checkpoint   s     $ 	OMNNN~%%OTOOO   EMMSSs
 
 
 
!2
 
 
 ! 	Uv U U>Bl>O>O>Q>QU U U  
 r#)S)S)S)STTTUVWWr%   )r   )N)"rC   
__module____qualname____doc__r   r   strr   __annotations__	Exceptionr   r   r   r	   r   r'   r(   
FileSystemrA   propertyr    r   intrO   rQ   staticmethodrY   classmethodr
   osPathLiker   r   r   r/   r%   r$   r   r      s        ! !F d38n%%%%.////I
III26x/666 	 hU($sCx.89:    <@'*"78???MMMN0c3h0 0 0 0 X0 HGJ1 H H H XHV VC V V V V V:$# $ $ $ $ (#J1(( 
( ( ( \(  ?Cn
 n
C$%n
 %WZ%:;n
 
	n
 n
 n
 [n
` Y!!!$X$X!$$X	'	($X $X $X "!$X $X $Xr%   r   )r}   rb   loggingr   dataclassesr   pathlibr   typingr   r   r   r   r	   r
   pandasrz   r'   r   ray._private.dictr   ray.air.constantsr   r   r   ray.util.annotationsr   	getLoggerrC   r   r   r/   r%   r$   <module>r      so   				   				 ! ! ! ! ! !       : : : : : : : : : : : : : : : :      



 0 0 0 0 0 0         
 + * * * * *		8	$	$ 
XEX EX EX EX EX EX EX  EX EX EXr%   