o
    1 i4                     @   s  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Zd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d	Zed
efddZdejdefddZ dedejfddZ!edej"j#defddZ$edej"j#defddZ%ededej"j#fddZ&ededej"j#fddZ'ede
e deeef fd d!Z(ed"eeef defd#d$Z)e	%d*d&eeef d'e*de	eeef  fd(d)Z+dS )+    N)OrderedDict)AnyDictOptionalSequenceTypeUnion)DeveloperAPI)NotSerializable)FlexDict)RepeatedSimplexZ__not_serializable__objc                 C   s   t | tjr
t| S t | tjrt| S t | tjrt| S t | tjr(t	| S t | tj
rC|  }t|D ]
\}}t|||< q6|S | S )zConvert an object that is a numpy type to a python type.

    If the object is not a numpy type, it is returned unchanged.

    Args:
        obj: The object to convert.
    )
isinstancenpintegerintZfloatingfloatZbool_boolZstr_strndarraytolist	enumerate"convert_numpy_to_python_primitives)r   retiv r   i/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/ray/rllib/utils/serialization.pyr      s   	r   arrayreturnc                 C   s.   t  }t||  tt| 	dS )zPack numpy ndarray into Base64 encoded strings for serialization.

    This function uses numpy.save() instead of pickling to ensure
    compatibility.

    Args:
        array: numpy ndarray.

    Returns:
        b64 escaped string.
    ascii)
ioBytesIOr   savebase64	b64encodezlibcompressgetvaluedecode)r    bufr   r   r   _serialize_ndarray/   s   r-   
b64_stringc                 C   s    t jttt| ddS )zUnpack b64 escaped string into numpy ndarray.

    This function assumes the unescaped bytes are of npy format.

    Args:
        b64_string: Base64 escaped string.

    Returns:
        numpy ndarray.
    T)Zallow_pickle)r   loadr#   r$   r(   
decompressr&   	b64decode)r.   r   r   r   _deserialize_ndarray@   s   r2   spacec                 C   s  | du rdS dt jjdtfdd}dt jjdtfdd}dt jjdtfdd	}dt jjdtfd
d}dt jjdtfdd}dt jjdtfdd}dtdtfdd}dt	dtfdd}dt
dtfdd}	dddtfdd}
t| t jjrw|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|
| S t| tr|| S t| t	r|| S t| t
r|	| S tdt| )zSerialize a gym Space into a JSON-serializable dict.

    Args:
        space: gym.spaces.Space

    Returns:
        Serialized JSON string.
    Nspr!   c                 S   s"   dt | jt | j| j| jjdS )Nbox)r3   lowhighshapedtype)r-   r6   r7   _shaper9   r   r4   r   r   r   _box]   s   zgym_space_to_dict.<locals>._boxc                 S   s,   dt | jd}t| drt | j|d< |S )Ndiscreter3   nstart)r   r?   hasattrr@   )r4   dr   r   r   	_discretef   s   
z$gym_space_to_dict.<locals>._discretec                 S   s   d| j dS )Nmulti-binaryr>   )r?   r;   r   r   r   _multi_binaryp   s   z(gym_space_to_dict.<locals>._multi_binaryc                 S   s   dt | j| jjdS )Nmulti-discrete)r3   nvecr9   )r-   rG   r9   r   r;   r   r   r   _multi_discretev   s   z*gym_space_to_dict.<locals>._multi_discretec                 S   s   ddd | j D dS )Ntuplec                 S      g | ]}t |qS r   gym_space_to_dict.0r4   r   r   r   
<listcomp>       z5gym_space_to_dict.<locals>._tuple.<locals>.<listcomp>r3   spacesrR   r;   r   r   r   _tuple}   s   z!gym_space_to_dict.<locals>._tuplec                 S   s   ddd | j  D dS )Ndictc                 S      i | ]	\}}|t |qS r   rK   rN   kr4   r   r   r   
<dictcomp>       z4gym_space_to_dict.<locals>._dict.<locals>.<dictcomp>rQ   )rR   itemsr;   r   r   r   _dict   s   z gym_space_to_dict.<locals>._dictc                 S   s   d| j | j| jjdS )Nsimplex)r3   r8   concentrationr9   )r:   r^   r9   r   r;   r   r   r   _simplex   s
   z#gym_space_to_dict.<locals>._simplexc                 S   s   dt | j| jdS )Nrepeated)r3   child_spacemax_len)rL   ra   rb   r;   r   r   r   	_repeated   s   z$gym_space_to_dict.<locals>._repeatedc                 S   s(   ddi}| j D ]
\}}t|||< q|S )Nr3   	flex_dict)rR   rL   )r4   rB   rX   sr   r   r   
_flex_dict   s
   z%gym_space_to_dict.<locals>._flex_dictgym.spaces.Textc                 S   sB   t | dd }|d u rt | dd }|d u rtdd| j| j|dS )NZcharacter_setcharsetz9Text space must have a character_set or charset attributetext)r3   
min_length
max_lengthrh   )getattr
ValueErrorrj   rk   )r4   rh   r   r   r   _text   s   z gym_space_to_dict.<locals>._textz&Unknown space type for serialization, )gymrR   Boxr   DiscreteMultiBinaryMultiDiscreteTupler   r   r   r   Textrm   type)r3   r<   rC   rE   rH   rT   r\   r_   rc   rf   rn   r   r   r   rL   P   sB   
	



rL   c                 C   s(   dt | i}d| jv rt| j|d< |S Nr3   original_space)rL   __dict__space_to_dictrx   )r3   rB   r   r   r   rz      s   
rz   rB   c                    s>  | du rdS dt fdd dt dtjjf fdd}dt dtjjf fdd	}dt dtjjf fd
d}dt dtjjf fdd}dt dtjjfdd}dt dtjjfdd}dt dtf fdd}dt dtfdd}dt dt	fdd}	dt ddf fdd}
|||||||||	|
d
}| d }||vrt
d||| | S )zDe-serialize a dict into gym Space.

    Args:
        str: serialized JSON str.

    Returns:
        De-serialized gym space.
    NrB   c                 S   s,   |   }|d= d|v rt|d |d< |S )z?Common updates to the dict before we use it to construct spacesr3   r9   )copyr   r9   rB   r   r   r   r   __common   s
   z%gym_space_from_dict.<locals>.__commonr!   c                    s>   |   }|t| d t| d d tjjdi  |S )Nr6   r7   )r6   r7   r   )r{   updater2   ro   rR   rp   r|   r}   r   r   r<      s   

z!gym_space_from_dict.<locals>._boxc                       t jjdi  | S Nr   )ro   rR   rq   rB   r   r   r   rC         z&gym_space_from_dict.<locals>._discretec                    r   r   )ro   rR   rr   r   r   r   r   rE      r   z*gym_space_from_dict.<locals>._multi_binaryc                    s4   |   }|dt|d i tjjdi  |S )NrG   r   )r{   r~   r2   ro   rR   rs   r|   r   r   r   rH      s   z,gym_space_from_dict.<locals>._multi_discretec                 S   s    dd | d D }t jj|dS )Nc                 S   rJ   r   gym_space_from_dictrM   r   r   r   rO      rP   z7gym_space_from_dict.<locals>._tuple.<locals>.<listcomp>rR   rS   )ro   rR   rt   rB   rR   r   r   r   rT      s   z#gym_space_from_dict.<locals>._tuplec                 S   s(   t dd | d  D }tjj|dS )Nc                 S   rV   r   r   rW   r   r   r   rY     rZ   z6gym_space_from_dict.<locals>._dict.<locals>.<dictcomp>rR   rS   )r   r[   ro   rR   r   r   r   r   r   r\     s   
z"gym_space_from_dict.<locals>._dictc                    s   t di  | S r   r   r   r   r   r   r_     s   z%gym_space_from_dict.<locals>._simplexc                 S   s   t | d }t|| d dS )Nra   rb   )ra   rb   )r   r   )rB   ra   r   r   r   rc     s   z&gym_space_from_dict.<locals>._repeatedc                 S   s   dd |   D }t|dS )Nc                 S   s"   i | ]\}}|d kr|t |qS )r3   r   )rN   rX   re   r   r   r   rY     s   " z;gym_space_from_dict.<locals>._flex_dict.<locals>.<dictcomp>rS   )r[   r   r   r   r   r   rf     s   
z'gym_space_from_dict.<locals>._flex_dictrg   c                    r   r   )ro   rR   ru   r   r   r   r   rn     r   z"gym_space_from_dict.<locals>._text)
r5   r=   rD   rF   rI   rU   r]   r`   rd   ri   r3   z)Unknown space type for de-serialization, )r   ro   rR   rp   rq   rr   rs   r   r   r   rm   )rB   r<   rC   rE   rH   rT   r\   r_   rc   rf   rn   Z	space_mapZ
space_typer   r   r   r      s8   

	
r   c                 C   sZ   t | d }d| v r+d| d v sJ t| d d tr$t | d |_|S t| d |_|S rw   )r   r   r   rx   space_from_dict)rB   r3   r   r   r   r   3  s   r   argskwargsc                 C   s   | D ]"}z
t t | W q ty$ } z
td| d| d}~ww | D ]'\}}z
t t | W q) tyP } ztd| d| d| d}~ww dS )a  Check if parameters to a function are serializable by ray.

    Args:
        args: arguments to be checked.
        kwargs: keyword arguments to be checked.

    Raises:
        NoteSerializable if either args are kwargs are not serializable
            by ray.
    zVRLModule constructor arguments must be serializable. Found non-serializable argument: z .
Original serialization error: Nz^RLModule constructor arguments must be serializable. Found non-serializable keyword argument: z = )raygetput	TypeErrorr
   r[   )r   r   argerX   r   r   r   r   !check_if_args_kwargs_serializableB  s:   r   type_c                 C   s   t | tr| S | jd | j S )zConverts a type into its full classpath ([module file] + "." + [class name]).

    Args:
        type_: The type to convert.

    Returns:
        The full classpath of the given type, e.g. "ray.rllib.algorithms.ppo.PPOConfig".
    .)r   r   
__module____qualname__)r   r   r   r   serialize_typef  s   
r   Fmoduleerrorc                 C   s   t | tr| S t | trBz| dd\}}t|} t| |W S  ttt	t
fyA } z|r6t
d|  d|W Y d}~| S d}~ww t
d|  d)aV  Resolves a class path to a class.
    If the given module is already a class, it is returned as is.
    If the given module is a string, it is imported and the class is returned.

    Args:
        module: The classpath (str) or type to resolve.
        error: Whether to throw a ValueError if `module` could not be resolved into
            a class. If False and `module` is not resolvable, returns None.

    Returns:
        The resolved class or `module` (if `error` is False and no resolution possible).

    Raises:
        ValueError: If `error` is True and `module` cannot be resolved.
    r      z2Could not deserialize the given classpath `module=z` into a valid python class! Make sure you have all necessary pip packages installed and all custom modules are in your `PYTHONPATH` env variable.Nz
`module` (z$ must be type or string (classpath)!)r   rv   r   rsplit	importlibimport_modulerl   ModuleNotFoundErrorImportErrorAttributeErrorrm   )r   r   module_path
class_namer   r   r   r   deserialize_typex  s&   






r   )F),r&   r   r#   r(   collectionsr   typingr   r   r   r   r   r   Z	gymnasiumro   numpyr   r   Zray.rllib.utils.annotationsr	   Zray.rllib.utils.errorr
   Zray.rllib.utils.spaces.flexdictr   Zray.rllib.utils.spaces.repeatedr   Zray.rllib.utils.spaces.simplexr   ZNOT_SERIALIZABLEr   r   r   r-   r2   rR   ZSpacerL   rz   r   r   r   r   r   r   r   r   r   r   <module>   sP     wb #
