o
    1 iX                     @   s  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mZmZ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mZ d dlmZ d dlmZ edZeeZde
e d	eeee f fd
dZ d	ee!e"f fddZ#de	e!ef fddZ$ded	e"fddZ%		d deeg ef ee	e!ef gef f dee	e!ef  dedee! ded	eg ef fddZ&G dd de j'Z(G dd dZ)dS )!    N)	AnyCallableContextManagerDictListOptionalTupleTypeVarUnion)ActorHandle)StartTracebackStartTracebackWithWorkerRankfind_free_port)RayActorError)	ObjectRefTremote_valuesreturnc                 C   s   |   }t|dkr_t|\}}|D ]E}zt| W q tyB } z| |}td| d d|fW  Y d}~  S d}~w t	yX } z| |}t
|d|d}~ww t|dks
dS )a$  Check for actor failure when retrieving the remote values.

    Args:
        remote_values: List of object references from Ray actor methods.

    Returns:
        A tuple of (bool, Exception). The bool is
        True if evaluating all object references is successful, False otherwise.
    r   zWorker z has failed.FN)Zworker_rank)TN)copylenraywaitgetr   indexloggerinfo	Exceptionr   )r   
unfinishedfinishedZ
object_refexcZfailed_actor_rankZfailed_worker_rank r    e/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/ray/train/_internal/utils.pycheck_for_failure!   s,   

r"   c                  C   s   t j } t }| |fS )z4Returns the IP address and a free port on this node.)r   utilZget_node_ip_addressr   )addrportr    r    r!   get_address_and_portG   s   
r&   env_varsc                 C   s"   dd |   D }tj| dS )zyUpdates the environment variables on this worker process.

    Args:
        env_vars: Environment variables to set.
    c                 S   s   i | ]	\}}|t |qS r    )str).0kvr    r    r!   
<dictcomp>U   s    z#update_env_vars.<locals>.<dictcomp>N)itemsosenvironupdate)r'   Z	sanitizedr    r    r!   update_env_varsO   s   r1   fnc                    s<   t | j }t jjt jjt jjh t fdd|D S )a  Counts the number of required parameters of a function.

    NOTE: *args counts as 1 required parameter.

    Examples
    --------

    >>> def fn(a, b, /, c, *args, d=1, e=2, **kwargs):
    ...    pass
    >>> count_required_parameters(fn)
    4

    >>> fn = lambda: 1
    >>> count_required_parameters(fn)
    0

    >>> def fn(config, a, b=1, c=2):
    ...     pass
    >>> from functools import partial
    >>> count_required_parameters(partial(fn, a=0))
    1
    c                    s(   g | ]}|j tjjkr|j v r|qS r    )defaultinspect	Parameteremptykind)r)   pZpositional_param_kindsr    r!   
<listcomp>x   s
    z-count_required_parameters.<locals>.<listcomp>)	r4   	signature
parametersvaluesr5   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDVAR_POSITIONALr   )r2   paramsr    r9   r!   count_required_parametersY   s   
rB   
train_funcFconfigtrain_func_contextfn_arg_namediscard_returnsc           	         s   t }|rtfdd}|n|dkr&| d| d}t||dkrA du r0i n  t fdd}|S tfd	d}|S )
a  Validates and constructs the training function to execute.
    Args:
        train_func: The training function to execute.
            This can either take in no arguments or a ``config`` dict.
        config (Optional[Dict]): Configurations to pass into
            ``train_func``. If None then an empty Dict will be created.
        train_func_context: Context manager for user's `train_func`, which executes
            backend-specific logic before and after the training function.
        fn_arg_name (Optional[str]): The name of training function to use for error
            messages.
        discard_returns: Whether to discard any returns from train_func or not.
    Returns:
        A valid training function.
    Raises:
        ValueError: if the input ``train_func`` is invalid.
    c               
      s4   z
 | i | W d S  t y } zt|d }~ww Nr   r   )argskwargse)rC   r    r!   discard_return_wrapper   s   z4construct_train_func.<locals>.discard_return_wrapper   z: should take in 0 or 1 required arguments, but it accepts z required arguments instead.Nc               
      sV   z   W  d    W S 1 sw   Y  W d S  t y* }  zt| d } ~ ww rH   rI   rL   )rD   rE   wrapped_train_funcr    r!   train_fn   s   (z&construct_train_func.<locals>.train_fnc               
      sT   z    W  d    W S 1 sw   Y  W d S  t y) }  zt| d } ~ ww rH   rI   rO   )rE   rP   r    r!   rQ      s   ()rB   	functoolswraps
ValueError)	rC   rD   rE   rF   rG   Znum_required_paramsrM   err_msgrQ   r    )rD   rC   rE   rP   r!   construct_train_func   s(   rV   c                       s$   e Zd ZdZi Z fddZ  ZS )	SingletonzSingleton Abstract Base Class

    https://stackoverflow.com/questions/33364070/implementing
    -singleton-as-metaclass-but-for-abstract-classes
    c                    s0   | | j vrtt| j|i || j | < | j |  S rH   )
_instancessuperrW   __call__)clsrJ   rK   	__class__r    r!   rZ      s   

zSingleton.__call__)__name__
__module____qualname____doc__rX   rZ   __classcell__r    r    r\   r!   rW      s    rW   c                   @   s&   e Zd ZdZdefddZdd ZdS )ActorWrapperzDWraps an actor to provide same API as using the base class directly.actorc                 C   s
   || _ d S rH   )rd   )selfrd   r    r    r!   __init__   s   
zActorWrapper.__init__c                    s   t | j|  fddS )Nc                     s   t  j| i |S rH   )r   r   remote)rJ   rK   Zactor_methodr    r!   <lambda>   s    z*ActorWrapper.__getattr__.<locals>.<lambda>)getattrrd   )re   itemr    rh   r!   __getattr__   s   zActorWrapper.__getattr__N)r^   r_   r`   ra   r   rf   rl   r    r    r    r!   rc      s    rc   )rC   F)*abcrR   r4   loggingr.   typingr   r   r   r   r   r   r   r	   r
   r   Z	ray.actorr   Zray.air._internal.utilr   r   r   Zray.exceptionsr   Z	ray.typesr   r   	getLoggerr^   r   boolr   r"   r(   intr&   r1   rB   rV   ABCMetarW   rc   r    r    r    r!   <module>   sL    ,

&
+$

F