
    Vh&                     v   d Z ddlZddlmZ ddlZddlZddlmZ ddlZ	ddl
Z
ddlmZmZ ddlmZ ddlmZmZ e	j        Zd	 Zd
 Z G d de          Z G d de          Zdg dddddej        de	j        eef         de	j        e         de	j        e         de	j        e	j        eef                  defdZdS )a*  
DecoratedMain is the main abstraction used inside Dora.
This defines the core interface that needs to be fullfilled
for Dora to be able to handle an experiment.

This is also where the end user will specify how to launch job, default
Slurm configuration, storage location, naming conventions etc.
    N)OrderedDict)Path   )
DoraConfigSlurmConfig)
NamesMixin)XP_contextc                 |    |                      dd          \  }}t          j        |          }t          ||          S )N.r   )rsplit	importlibimport_modulegetattr)	full_namemodule_namefun_namemodules       O/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/dora/main.py
_load_mainr       s<    %,,S!44K$[11F68$$$    c                 V    | dk    r"t           j        |          j        }|d S |j        S | S )N__main__)sysmodules__spec__name)r   specs     r   get_module_namer   &   s3    {6"+<49r   c                   P   e Zd ZdZdZdedefdZd Zde	j
        e         defd	Zd
 Zd Zde	j        e         defdZde	j
        e         fdZdefdZdede	j        e         fdZdedefdZd Zde	j        de	j
        e         fdZdede	j
        e         fdZdefdZdS )DecoratedMaina  
    Main function that will actually run the XP, wrapped with tons of meta-informations.

    Args:
        main (callable, taking no argument): main function for the experiment as provided
            by the user.
        dora (DoraConfig): configuration for Dora.
    Fmaindorac                    || _         || _        t          |j                  }|d| _        d| _        n6d|v r$|                    dd          \  | _        | _        nd| _        || _        | j        | _        |j        dz   |j        z   | _	        d S )Nunknowntrainr   r   )
r"   r#   r   
__module__packagemain_moduler   r   __name__
_full_name)selfr"   r#   r   s       r   __init__zDecoratedMain.__init__<   s    		%do66 %DL&Dk!!1<1C1CC1K1K.d..(#. L	/C/$-?r   c                 T   |                                  }|                     |          s|                                 S |                     |          }|                     |           t          j        |          5  |                                 cd d d            S # 1 swxY w Y   d S N)	_get_argv
_is_active_mainget_xpinit_xpr
   enter_xp)r,   argvxps      r   __call__zDecoratedMain.__call__O   s    ~~t$$ 	 ::<<[[Rr"" 	  	 ::<<	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   <BB!$B!r6   returnc                     dS NT r,   r6   s     r   r1   zDecoratedMain._is_activeX   s    tr   c                 *    |                                  S r/   r"   r,   s    r   r2   zDecoratedMain._main[   s    yy{{r   c                      t           | j        ffS r/   )r   r+   r@   s    r   
__reduce__zDecoratedMain.__reduce__^   s    DO---r   c                     t                      )z0Return an XP given a list of arguments.
        NotImplementedErrorr=   s     r   r3   zDecoratedMain.get_xpa   s     "###r   c                 *    t           j        dd          S )Nr   )r   r6   r@   s    r   r0   zDecoratedMain._get_argvf   s     x|r   r7   c                    |j                             dd           t          j        |j        t          |j        d                     |j        |j        j        j                            ddd           |j        j                            ddd           	 |j        j        j        	                    d           |j        j        	                    d           n# t          $ r Y nw xY wt          j        |j        t          |j        d                     	 |j        	                    d           n# t          $ r Y nw xY w|S )ag  
        Initialize the XP folder. Once this is done, the XP can be retrieved
        from its signature. This is done automatically before running,
        or when using the `--init` flag of the `dora grid` command.

        This will also initialize the shared XP folder so that the XP hyper-params
        can be easily shared using its signature.
        T)exist_okparentswNi  )rH   rI   mode)foldermkdirjsondumpr6   open_argv_cache_shared_argv_cacheparentchmodPermissionErrorr,   r7   s     r   r4   zDecoratedMain.init_xpl   sP    		t444	"'444555 ,!(/55tTX]5^^^!(..dQV.WWW%,399%@@@%,2259999"   IbgtB$93??@@@%++E2222"   	s%   AC 
C,+C,D8 8
EEsigc                 `   t          || j        dg           }|j                                        r&t	          j        t          |j                            S |j        ?|j                                        r&t	          j        t          |j                            S t          d|           )zReturns the argv used to obtain a given signature.
        This can only work if an XP was previously ran with this signature.
        N)rW   r#   cfgr6   z)Could not find experiment with signature )	r	   r#   rQ   existsrN   loadrP   rR   RuntimeError)r,   rW   r7   s      r   get_argv_from_sigzDecoratedMain.get_argv_from_sig   s     CdiT;;;>  "" 	R9T".11222".23H3O3O3Q3Q.9T""788999P3PPQQQr   c                 R    |                      |                     |                    S )zcReturns the XP from the signature. Can only work if such an XP
        has previously ran.
        )r3   r]   )r,   rW   s     r   get_xp_from_sigzDecoratedMain.get_xp_from_sig   s$     {{411#66777r   c                     d| j          dS )NzDecoratedMain()r?   r@   s    r   __repr__zDecoratedMain.__repr__   s    ,	,,,,r   argc                     t                      )a
  Convert a Python value to argv. arg can be either:
        - a list, then each entry will be converted and all argv are concatenated.
        - a str, then it is directly an argv entry.
        - a dict, then each key, value pair is mapped to an argv entry.
        rD   )r,   rc   s     r   value_to_argvzDecoratedMain.value_to_argv   s     "###r   c                 L    |j                                          |j         j        S )a  Return the metrics for a given XP. By default this will look into
        the `history.json` file, that can be populated with the Link class.

        Can be overriden, but metrics should still be returned as a list
        of dicts, possibly with nested dicts.
        )linkr[   historyrV   s     r   get_xp_historyzDecoratedMain.get_xp_history   s     	wr   c                     t                      S zEReturn default Slurm config for the launch and grid actions.
        )r   r@   s    r   get_slurm_configzDecoratedMain.get_slurm_config   s     }}r   N)r*   r'   __qualname____doc___slowMainFunr   r-   r8   tpListstrboolr1   r2   rB   Sequencer	   r3   r0   r4   r]   r_   rb   Anyre   dictri   r   rl   r<   r   r   r!   r!   1   s         E@W @J @ @ @ @&     rws|       . . .$2;s+ $ $ $ $ $
273<    "    6
RS 
RR[-= 
R 
R 
R 
R83 82 8 8 8 8- - -$ $BGCL $ $ $ $     +      r   r!   c                        e Zd ZdZ	 ddededej        dej	        e
         def
 fd	Zd
ej        e         defdZdej        dej        e         fdZdedefdZde
f fdZ xZS )ArgparseMaina  Implementation of `DecoratedMain` for XP that uses argparse.

    Args:
        main : main function to wrap.
        dora : Dora config, containing the exclude and dir fields.
        parser : parser to use, and to derive default values from.
        slurm : default slurm config for scheduling jobs.
        use_underscore : if False, scheduling a job as `launcher(batch_size=32)`
            will translate to the command-line `--batch-size=32`,
            otherwise, it will stay as `--batch_size=32`.
    NTr"   r#   parserslurmuse_underscorec                 v    t                                          ||           || _        || _        || _        d S r/   )superr-   rz   r|   r{   )r,   r"   r#   rz   r{   r|   	__class__s         r   r-   zArgparseMain.__init__   s7    t$$$,


r   r6   r9   c                 4   t          |          }| j                            |          }g }|j                                        D ]:\  }}| j                            |          |k    r|                    ||f           ;t          | j        |||          }|S )N)r#   rY   r6   delta)	listrz   
parse_args__dict__itemsget_defaultappendr	   r#   )r,   r6   argsr   keyvaluer7   s          r   r3   zArgparseMain.get_xp   s    Dzz{%%d++---// 	+ 	+JC{&&s++u44c5\***TYDt5AAA	r   rc   c                    g }t          |t                    r|                    |           nt          |t                    rp|                                D ]Z\  }}| j        s|                    dd          }|du r|                    d|            ?|                    d| d|            [nLt          |t          t          f          r|D ]}|| 	                    |          z  }nt          d|           |S )N_-Tz--=z5Can only process dict, tuple, lists and str, but got )
isinstancers   r   rw   r   r|   replacer   tuplere   
ValueError)r,   rc   r6   r   r   parts         r   re   zArgparseMain.value_to_argv   s0   c3 	\KKT"" 	\!iikk 4 4
U* 0++c3//CD==KK
S

++++KK 2S 2 25 2 233334 dE]++ 	\ 1 1**40001 ZUXZZ[[[r   r7   c                 X    t                      }|j        J |j        D ]
\  }}|||<   |S r/   )r   r   )r,   r7   partsr   r   s        r   get_name_partszArgparseMain.get_name_parts   s>    x###8 	  	 KD%E$KKr   c                 `    | j         | j         S t                                                      S rk   )r{   r~   rl   )r,   r   s    r   rl   zArgparseMain.get_slurm_config   s+     :!:ww'')))r   r;   )r*   r'   rm   rn   rp   r   argparseArgumentParserrq   Optionalr   rt   r-   ru   rs   r	   r3   rv   rr   re   r   r   rl   __classcell__)r   s   @r   ry   ry      s       
 
 QU W J @W K0IM     2;s+      BGCL    &     *+ * * * * * * * * * *r   ry   z	./outputsT)direxcluder{   sharedr|   rz   r   r   r{   r   r|   c                :     dt           f fd}|S )a  Nicer version of `ArgparseMain` that acts like a decorator, and directly
    exposes the most useful configs to override.

    Args:
        parser: parser to use, and to derive default values from.
        exclude: list of patterns of arguments to exclude from the computation
            of the XP signature.
        dir: path to store logs, checkpoints, etc. to.
        slurm: default slurm config for scheduling jobs.
        shared: path to the shared XP repository.
        use_underscore: if False, scheduling a job as `launcher(batch_size=32)`
            will translate to the command-line `--batch-size=32`,
            otherwise, it will stay as `--batch_size=32`.
        **kwargs: extra args are passed to `DoraConfig`.
    r"   c                     t          dt                    d nt                    t                    d}t          | |          S )N)r   r   r   )r|   r{   r<   )r   r   r   ry   )	r"   r#   r   r   kwargsrz   r   r{   r|   s	     r   
_decoratorz!argparse_main.<locals>._decorator	  se     S		!>44tF||MM  	 
 D$~UZ[[[[r   )rp   )rz   r   r   r{   r   r|   r   r   s   ``````` r   argparse_mainr      sa    ,\ \ \ \ \ \ \ \ \ \ \ \ \ r   ) rn   r   collectionsr   r   rN   pathlibr   typingrq   r   confr   r   namesr   r7   r	   r
   Callablerp   r   r   r!   ry   r   Unionrs   ru   r   rt   r   r<   r   r   <module>r      s     # # # # # #                



 ) ) ) ) ) ) ) )               +% % %  @ @ @ @ @J @ @ @F<* <* <* <* <*= <* <* <*@ .9.048=A)-  (1 xT	*;s+ [1 +bhsDy&9:	
 #'     r   