o
    )Tib                     @   s^  d Z ddlZddlZddlZddlmZmZ ddlmZm	Z	m
Z
mZ ddlmZ ddlmZmZmZmZmZmZmZ ddlmZ dd	l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) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/ ddlm0Z0 dgZ1ej2Z3ej4Z5G dd deZ6de7fddZ8dd Z9dd Z:dd Z;dd Z<de=fddZ>dS )zCMethods to add arguments based on class/method/function signatures.    N)SUPPRESSArgumentParser)AnyCallableOptionalUnion   )_ActionConfigLoad)LoggerPropertyget_class_instantiatorget_generic_originget_unaliased_typeis_final_classis_subclassis_subclasses_disabled)	Namespace)attrs_supportget_doc_short_descriptionis_attrs_classis_pydantic_model)	ParamDataget_parameter_originsget_signature_parameters)ActionTypeHintLazyInitBaseClasscallable_instancesget_subclass_namesis_list_pathlikeis_optionalnot_required_typessequence_origin_types)NoneTypeget_import_pathget_private_kwargsget_typehint_originiter_to_set_str)register_pydantic_typeSignatureArgumentsc                   @   s@  e Zd ZdZ								d(dedee deded	eee	e
eef  d
eeeeef   dedededee fddZ						d)dededee deded
eeeeef   dededee fddZ						d)dedee deded
eeeeef   dededee fddZ								d*dee deded
eeeeef   dedededeee  dee dee fddZddddddefdee dee d
eee  dededededeee  d	efddZ						d+d eeeed!f f deded
eee  ded"ed#edefd$d%Z				d,d&d'ZdS )-r'   zTMethods to add arguments based on signatures to an :class:`ArgumentParser` instance.NTFtheclass
nested_keyas_groupas_positionaldefaultskipinstantiatefail_untypedsub_configsreturnc
                    sX  t |}tt|std| t|tttfs:t|t	r$t||s:t
|js3t|jr3t||s:td| t|
dddd\}}}| j|d|||||	|||d}|rp[t |rb|d nd|}t|t	rr|  }n"t|jrt|}fdd	|D   fd
d|D }|r| |rfdd| D }| jdi | |S )aZ  Adds arguments from a class based on its type hints and docstrings.

        Note: Keyword arguments without at least one valid type are ignored.

        Args:
            theclass: Class from which to add arguments.
            nested_key: Key for nested namespace.
            as_group: Whether arguments should be added to a new argument group.
            as_positional: Whether to add required parameters as positional arguments.
            default: Default value used to override parameter defaults.
            skip: Names of parameters or number of positionals that should be skipped.
            instantiate: Whether the class group should be instantiated by ``instantiate_classes``.
            fail_untyped: Whether to raise exception if a required parameter does not have a type.
            sub_configs: Whether subclass type hints should be loadable from inner config file.

        Returns:
            The list of arguments added.

        Raises:
            ValueError: When not given a class.
            ValueError: When there are required parameters without at least one valid type.
        z7Expected 'theclass' parameter to be a class type, got: zPExpected 'default' to be dict, Namespace, lazy instance or dataclass-like, got: N)linked_targetshelprequired)r0   r.   r2   r3   . c                    s   h | ]
}|t  d  qS N)len.0kprefix L/home/ubuntu/.local/lib/python3.10/site-packages/jsonargparse/_signatures.py	<setcomp>|   s    z9SignatureArguments.add_class_arguments.<locals>.<setcomp>c                    s   g | ]}| vr|qS r>   r>   r9   )argsr>   r?   
<listcomp>}   s    z:SignatureArguments.add_class_arguments.<locals>.<listcomp>c                    s"   i | ]\}}|vr | |qS r>   r>   )r:   r;   v)r=   r-   r>   r?   
<dictcomp>      " z:SignatureArguments.add_class_arguments.<locals>.<dictcomp>r>   )r   inspectisclassr   
ValueError
isinstancer!   dictr   r   r   	__class__r   r#   _add_signature_argumentssetlazy_get_init_argsas_dictis_convertible_to_dictconvert_to_dictupdateitemsset_defaults)selfr(   r)   r*   r+   r,   r-   r.   r/   r0   kwargsunaliased_class_typer2   help__
added_argsdefaultsskip_not_addedr>   )rA   r=   r-   r?   add_class_arguments-   sj   #	



z&SignatureArguments.add_class_arguments	themethodc	           
   
   C   sX   t |}	tt|	stdt|	|rtt|	|std| j||||||||dS )a  Adds arguments from a class based on its type hints and docstrings.

        Note: Keyword arguments without at least one valid type are ignored.

        Args:
            theclass: Class which includes the method.
            themethod: Name of the method for which to add arguments.
            nested_key: Key for nested namespace.
            as_group: Whether arguments should be added to a new argument group.
            as_positional: Whether to add required parameters as positional arguments.
            skip: Names of parameters or number of positionals that should be skipped.
            fail_untyped: Whether to raise exception if a required parameter does not have a type.
            sub_configs: Whether subclass type hints should be loadable from inner config file.

        Returns:
            The list of arguments added.

        Raises:
            ValueError: When not given a class or the name of a method of the class.
            ValueError: When there are required parameters without at least one valid type.
        z2Expected "theclass" argument to be a class object.zCExpected "themethod" argument to be a callable member of the class.r0   )	r   rF   rG   r   rH   hasattrcallablegetattrrL   )
rU   r(   r^   r)   r*   r+   r-   r/   r0   unaliased_typer>   r>   r?   add_method_arguments   s    z'SignatureArguments.add_method_argumentsfunctionc           	   
   C   sL   t |stdd}t|drt|jr|j}d}| j||||||||dS )a  Adds arguments from a function based on its type hints and docstrings.

        Note: Keyword arguments without at least one valid type are ignored.

        Args:
            function: Function from which to add arguments.
            nested_key: Key for nested namespace.
            as_group: Whether arguments should be added to a new argument group.
            as_positional: Whether to add required parameters as positional arguments.
            skip: Names of parameters or number of positionals that should be skipped.
            fail_untyped: Whether to raise exception if a required parameter does not have a type.
            sub_configs: Whether subclass type hints should be loadable from inner config file.

        Returns:
            The list of arguments added.

        Raises:
            ValueError: When not given a callable.
            ValueError: When there are required parameters without at least one valid type.
        z5Expected "function" argument to be a callable object.NrK   __call__r_   )ra   rH   r`   r   rK   rL   )	rU   re   r)   r*   r+   r-   r/   r0   method_namer>   r>   r?   add_function_arguments   s    z)SignatureArguments.add_function_argumentsr2   r3   c                 C   s  t ||| jd}dd |pg D }|rMt|dks"tdd |D r)td| dd	 |d
|d  D }||d d
 }| jd| d|d  d d|rT|d nd }|D ]$}|rc|j|v rcqY||j | jv r}td|j d| d||j  dqY|d
ur|}nt||| jd}|rt	||n|}| j
||||t|dk|	d}g }|D ]}| j||||dd	 |pg D |||
|d	 q|S )a  Adds arguments from parameters of objects based on signatures and docstrings.

        Args:
            function_or_class: Object from which to add arguments.
            method_name: Class method from which to add arguments.
            nested_key: Key for nested namespace.
            as_group: Whether arguments should be added to a new argument group.
            as_positional: Whether to add required parameters as positional arguments.
            skip: Names of parameters or number of positionals that should be skipped.
            fail_untyped: Whether to raise exception if a required parameter does not have a type.
            sub_configs: Whether subclass type hints should be loadable from inner config file.
            instantiate: Whether the class group should be instantiated by ``instantiate_classes``.

        Returns:
            The list of arguments added.

        Raises:
            ValueError: When there are required parameters without at least one valid type.
        loggerc                 S   s"   g | ]}t |tr|d kr|qS )r   )rI   intr:   sr>   r>   r?   rB     rE   z?SignatureArguments._add_signature_arguments.<locals>.<listcomp>r   c                 s   s    | ]}|d kV  qdS )r   Nr>   r:   pr>   r>   r?   	<genexpr>      z>SignatureArguments._add_signature_arguments.<locals>.<genexpr>z*Unexpected number of positionals to skip: c                 S   s   h | ]}|j qS r>   namern   r>   r>   r?   r@     s    z>SignatureArguments._add_signature_arguments.<locals>.<setcomp>Nr   zSkipping parameters z	 because z% positionals requested to be skipped.--r5   r6   zUnable to add parameter 'z' from z because argument 'z' already exists.)config_loadr.   c                 S   s   h | ]	}t |tr|qS r>   )rI   strrl   r>   r>   r?   r@   6      )r-   r/   r0   r2   r+   )r   rj   r8   anyrH   debugrs   _option_string_actionsr   rb   _create_group_if_requested_add_signature_parameter)rU   function_or_classrg   r)   r*   r+   r-   r/   r0   r.   r2   r3   paramsskip_positionalsnamesr=   param	doc_group	component	containerrZ   r>   r>   r?   rL      s^   !

z+SignatureArguments._add_signature_argumentsrZ   c               
      sP  |j }|j}|j}|tkr#|j}|tkr#t|rd }nt|tv r#t}|t	j
kr-d}d}n*|t	jkr9|tk}d}n|t	jkrE|tk}d}n|d u rP|tk}d}ntd| t|j|j}d| d| d}|sw|tkrwt}|rsd n|}d}d}|r|
d ur||
v rd }d}d}|s|d dkrd S |r||v r| j|d	  d S t|r|jj|  }|tkr|stt|tf }d
|vr|j|d
< |s||d< |d u rt|ts|st| }n|r|rd|d< d}t|}|r|d nd| }|r|r|s|nd| g}|jr4|}t|tst |d}d!dd |jD }||j"v r)|j"| }n|j#d| d|d}|t$t%t&t'hv sIt(|t$t%t&fsI|rR||d< t)| nn|tkrzKt*j+|dd}||d< ||d}|r| d  fdd|pyg D }||d< nt)| |o|pt*,|pt-|}t*j.||||| j|d}W n t/y } z| j|t$|  W Y d }~nd }~ww d|v sd|v r|||	d }|r|0| t*1  |j2|i |}W d    n	1 sw   Y  |d ur||_3|rt4|dkr||j3d< |5| d S |r$|r&t/d!| d"| d#d S d S )$NTFz'The code should never reach here: kind=zSkipping parameter "z" from "z" because of: r   rY   z"Parameter requested to be skipped.r3   r,   r4   r5   r6   rt   parserz; c                 s   s    | ]}t |V  qd S r7   )rv   )r:   or>   r>   r?   rp     rq   z>SignatureArguments._add_signature_parameter.<locals>.<genexpr>z Conditional arguments [origins: ]rr   type)all_subtypes)r/   r0   .init_args.c                    s&   h | ]}|  r|t d  qS r7   )
startswithr8   rl   r<   r>   r?   r@     s   & z>SignatureArguments._add_signature_parameter.<locals>.<setcomp>r-   )rA   rV   enable_pathr   rj   sub_add_kwargsaction)r/   r0   r.   zXWith fail_untyped=True, all mandatory parameters must have a supported type. Parameter 'z' from 'z' does not specify a type.)6rs   kind
annotationinspect_emptyr,   r   r$   r   r   kindsPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDKEYWORD_ONLYRuntimeErrorr   r   parentr   rj   ry   is_factory_class__dataclass_fields__default_factoryr   r   docobjectr   r   originrI   r   rb   joingroupsadd_argument_grouprv   rk   floatboolr   r&   r   is_subclass_typehintis_return_subclass_typehintr   prepare_add_argumentrH   rR   allow_default_instance_contextadd_argumentr   r8   append) rU   r   r)   r   rZ   r-   r/   r+   r0   r.   r2   r,   rV   rs   r   r   is_requiredis_non_positionalsrcskip_messageis_required_link_targetr   subclasses_disableddestrA   r   
group_namer   subclass_skipr   exr   r>   r<   r?   r|   ?  s   





*





 



z+SignatureArguments._add_signature_parameter2CONFIG | CLASS_PATH_OR_NAME | .INIT_ARG_NAME VALUEeOne or more arguments specifying "class_path" and "init_args" for any subclass of %(baseclass_name)s.	baseclass.r4   metavarc	              	      s  t |tur	|f}t|tsJ |rtdd |D s"td| d}
t|dkr3t|d | jd}
| j| ||
d|dd	}g }|durN fd
d|D }t	 t
| |d}tt|j}|	||d|i d d|	vrrd|	d< | j|d|||fd|d|	 dS )a  Adds arguments to allow specifying any subclass of the given base class.

        This adds an argument that requires a dictionary with a ``class_path``
        entry which must be a import dot notation expression. Optionally any
        init arguments for the class can be given in the ``init_args`` entry.
        Since subclasses can have different init arguments, the help does not
        show the details of the arguments of the base class. Instead a help
        argument is added that will print the details for a given class path.

        Args:
            baseclass: Base class or classes to use to check subclasses.
            nested_key: Key for nested namespace.
            as_group: Whether arguments should be added to a new argument group.
            skip: Names of parameters that should be skipped.
            required: Whether the argument group is required.
            metavar: Variable string to show in the argument's help.
            help: Description of argument to show in the help.
            **kwargs: Additional parameters like in :meth:`add_class_arguments`.

        Raises:
            ValueError: When given an invalid base class.
        c                 s   s    | ]
}t j|d dV  qdS )T)
also_listsN)r   r   )r:   cr>   r>   r?   rp     s    z<SignatureArguments.add_subclass_arguments.<locals>.<genexpr>zIExpected 'baseclass' to be a subclass type or a tuple of subclass types: Nr   r   ri   F)ru   r4   r.   c                    s   h | ]	}  d | qS )r   r>   rl   r)   r>   r?   r@     rw   z<SignatureArguments.add_subclass_arguments.<locals>.<setcomp>)rs   r   r   baseclass_name)r   r3   r,   T)r0   r.   )r   tuplerI   allrH   r8   r   rj   r{   r   r   r%   r   r   rR   r|   )rU   r   r)   r*   r-   r.   r4   r   r3   rV   r   grouprZ   r   str_baseclassr>   r   r?   add_subclass_arguments  sH   $



z)SignatureArguments.add_subclass_argumentsc	                 C   s   |r|d u r
t d| j| | }	|rk|d u r.t|tr*t|dkr*t|d }nt|}|d u r6t|n|}
| jt	||
d}	|rS|d urS|	j
d| t|dd t|rk|d urk|rk|dd	|	_||	_t|	_|	S )
Nz+A nested_key is mandatory to make required.r   r   rr   rt   )basetype)r   -rY   )rH   required_argsaddrI   r   r8   rv   get_object_namer   strip_titler   r	   rF   rG   replacer   group_classgroup_instantiate_classinstantiate_class)rU   objr)   r*   r   ru   config_load_typer4   r.   r   rs   r>   r>   r?   r{     s&   z-SignatureArguments._create_group_if_requested)NTFNNTTF)NTFNTF)TFNTFTNN)TNTFr   r   )TNFT)__name__
__module____qualname____doc__r   r   rv   r   r   rJ   r   r   rM   rk   listr]   rd   r   rh   rL   r   r   r|   r   r   r{   r>   r>   r>   r?   r'   *   sF   	

]	

4	
6	


]
	


 
	
Nr1   c                 C   s2   t | dr| jS t| dd ddddS )Nr   r5   [rY   r   r6   )r`   r   rv   splitr   )r   r>   r>   r?   r   0  s   
"r   c                 C   sX   z| | j\}}}W n ty   i }|}| j}Y nw t }|| jfi |||< d S r7   )get_value_and_parentr   KeyErrorr   r   )r   cfgvaluer   keyinstantiator_fnr>   r>   r?   r   6  s   
r   c                 C   s   | d urt dd|  } | S )Nz\.$r6   )resubstripr   r>   r>   r?   r   A  s   r   c                 C   s   | j tjkS r7   )rK   dataclasses_HAS_DEFAULT_FACTORY_CLASSr   r>   r>   r?   r   G  s   r   c                 C   s   t | pt| pt| S r7   )r   is_dataclassr   r   r   r>   r>   r?   rP   K  s   rP   c           	      C   s   t rdd l}|t| r|| S t| }i }t|  D ]2\}}t|}t|r/t|}n|t	v rL|
 }t|D ]\}}tt|rKt|||< q;|||< qt|rW|S t||dS )Nr   )
class_path	init_args)r   attrshasr   asdictvarsrS   rP   rQ   r    copy	enumerater   r"   )	r   r   
value_typer   rs   attr	attr_typenumitemr>   r>   r?   rQ   O  s(   


rQ   )?r   r   rF   r   argparser   r   typingr   r   r   r   _actionsr	   _commonr
   r   r   r   r   r   r   
_namespacer   
_optionalsr   r   r   r   _parameter_resolversr   r   r   
_typehintsr   r   r   r   r   r   r   r    _utilr!   r"   r#   r$   r%   r&   __all___ParameterKindr   _emptyr   r'   rv   r   r   r   r   rP   rJ   rQ   r>   r>   r>   r?   <module>   s8    $	(
    
