o
    ߥi6                     @   s  d Z 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 ddlmZ ddlmZ ddlmZmZ dd	lmZmZ dd
lmZ z
ddlmZmZ W n	 eyY   Y nw g dZdZdZ eZ!e" Z#dd Z$dd Z%dd Z&dd Z'dd Z(eddZ)daddZ*dd Z+d d! Z,d"d# Z-d$d% Z.d&d' Z/d(d) Z0G d*d+ d+ej1Z1G d,d- d-ej2Z2d.d/ Z3d0d1 Z4dbd4d5Z5e3Z6e4Z7e5Z8d6d7 Z9d8d9 Z:ed:ed:ed:ee'g d;d<e;e;e9e:e:e;ee'd=d>gd<e<ee'd?d@gd<ee'dAgd<ee'dBdCgd<dDeedEdFdGed:ed:ed:e;e9e:e:e;ee'd=d>gd<ee'd?d@gd<e<e<e<dHeedEdFdGdIZ=edJdK dLdK e(e
e>e?ej@ejAejBeCe(eDee(ee(ejEdMZFe*dNdOdK dPdQ ZGe-dNdRdS ZHe*dTdUdVdWdX ZIe*dYdZd[ ZJe-dYd\d] ZKe-d^d_d` ZLdS )cz<Custom datatypes (like datetime) serialization to/from JSON.    N
namedtuple)	timedelta)parse)Decimal)Fraction)partialwraps)
attrgettermethodcaller)
SortedList)CurrencyMoney)loadsdumpspretty
json_loads
json_dumpsjson_prettydumpencoderdecoder      c                 C   s
   | t _d S N)_localcoding)r    r   U/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/fileio/format/jsonplus.pyprefer>   s   
r   c                   C      t t d S r   )r   EXACTr   r   r   r   prefer_exactB      r!   c                   C   r   r   )r   COMPATr   r   r   r   prefer_compatF   r"   r$   c                    s   t  fdd|D S )a  Helper function that extracts a list of attributes from
    `value` object in a `dict`/mapping of (attr, value[attr]).

    Args:
        value (object):
            Any Python object upon which `getattr` can act.

        attrs (iterable):
            Any iterable containing attribute names for extract.

    Returns:
        `dict` of attr -> val mappings.

    Example:
        >>> getattrs(complex(2,3), ['imag', 'real'])
        {'imag': 3.0, 'real': 2.0}
    c                    s   g | ]	}|t  |fqS r   )getattr).0attrvaluer   r   
<listcomp>\   s    zgetattrs.<locals>.<listcomp>)dict)r)   attrsr   r(   r   getattrsJ   s   r-   c                    s   t   fdd}|S )a  Function decorator that wraps a function receiving
    keyword arguments into a function receiving a dictionary
    of arguments.

    Example:
        @kwargified
        def test(a=1, b=2):
            return a + b

        >>> test({'b': 3})
        4
    c                    s    di | S Nr   r   )kwargsconstructorr   r   kwargs_constructorm   s   z&kwargified.<locals>.kwargs_constructor)r	   )r1   r2   r   r0   r   
kwargified_   s   r3   _PredicatedEncoderz#priority predicate encoder typenameTc                    s\   |rt d nt d du r#td dkr!d d jd nd fd	d
}|S )a}  A decorator for registering a new encoder for object type
    defined either by a `classname`, or detected via `predicate`.

    Predicates are tested according to priority (low to high),
    but always before classname.

    Args:
        classname (str):
            Classname of the object serialized, equal to
            ``type(obj).__name__``.

        predicate (callable, default=None):
            A predicate for testing if object is of certain type.
            The predicate shall receive a single argument, the object
            being encoded, and it has to return a boolean `True/False`.
            See examples below.

        priority (int, default=None):
            Predicate priority. If undefined, encoder is added at
            the end, with lowest priority.

        exact (bool, default=True):
            Determines the kind of encoder registered, an exact
            (default), or a compact representation encoder.

    Examples:
        @encoder('mytype')
        def mytype_exact_encoder(myobj):
            return myobj.to_json()

        Functional discriminator usage is appropriate for serialization
        of objects with a different classname, but which can be encoded
        with the same encoder:

        @encoder('BaseClass', lambda obj: isinstance(obj, BaseClass))
        def all_derived_classes_encoder(derived):
            return derived.base_encoder()
    exactcompatN	predicater   d   i  c                    s4   rd  t|   | S d  |  | S )Nr7   	classname)addr4   
setdefaultfr:   r7   prioritysubregistryr   r   
_decorator   s   zencoder.<locals>._decorator)_encode_handlerslenr@   )r:   r7   r@   r5   rB   r   r?   r   r   x   s   '
r   c                 C   sv   t d d D ]}|| r|j|| d  S qt| j}|t d d v r3|t d d | | dS tt| d )zqSerialization handlers for types unsupported by `simplejson` 
    that try to preserve the exact data types.
    r5   r7   )	__class__	__value__r:    is not JSON serializable)rC   r7   typenamer   type__name__	TypeErrorreprobjhandlerr:   r   r   r   _json_default_exact   s   


rP   c                 C   sh   t d d D ]}|| r||   S qt| j}|t d d v r,t d d | | S tt| d )zaSerialization handlers that try to dump objects in
    compatibility mode. Similar to above.
    r6   r7   r:   rG   )rC   r7   r   rI   rJ   rK   rL   rM   r   r   r   _json_default_compat   s   

rQ   c                    s    fdd}|S )a<  A decorator for registering a new decoder for `classname`.
    Only ``exact`` decoders can be registered, since it is an assumption
    the ``compat`` mode serializes to standard JSON.

    Example:
        @decoder('mytype')
        def mytype_decoder(value):
            return mytype(value, reconstruct=True)
    c                    s   t  |  d S r   )_decode_handlersr<   r=   r:   r   r   rB      s   zdecoder.<locals>._decoratorr   )r:   rB   r   rS   r   r      s   r   c                 C   s>   |  d}|rt |}|  d}|r||S td| | S )zDDeserialization handlers for types unsupported by `simplejson`.
    rE   rF   zUnknown class: '%s')getrR   rK   )r+   r:   r1   r)   r   r   r   _json_object_hook   s   


rU   c                 C   sZ   |  dttdttkr| tdddd n| tdd | dd | d	d d
S )z/Shape default arguments for encoding functions.r5   r   F)defaultuse_decimaltuple_as_arraynamedtuple_as_objectT)rV   
ignore_nan
separators),:for_jsonN)	popr%   r   CODING_DEFAULTr    updaterP   rQ   r<   kwr   r   r   _encoder_default_args   s   
	rd   c                 C   s   |  dti dS )z/Shape default arguments for decoding functions.object_hookN)ra   rU   rb   r   r   r   _decoder_default_args  s   rf   c                          e Zd Z fddZ  ZS )JSONEncoderc                    "   t | tt| jdi | dS )z^Constructor for simplejson.JSONEncoder, with defaults overriden
        for jsonplus.
        Nr   )rd   superrh   __init__selfrc   rE   r   r   rk   $     zJSONEncoder.__init__rJ   
__module____qualname__rk   __classcell__r   r   rn   r   rh   "      rh   c                       rg   )JSONDecoderc                    ri   )z^Constructor for simplejson.JSONDecoder, with defaults overriden
        for jsonplus.
        Nr   )rf   rj   ru   rk   rl   rn   r   r   rk   .  ro   zJSONDecoder.__init__rp   r   r   rn   r   ru   ,  rt   ru   c                  O      t | tj| i |S r   )rd   jsonr   parc   r   r   r   r   6     r   c                  O   rv   r   )rf   rw   r   rx   r   r   r   r   ;  rz   r       r\   z: c                 K   s4   | d| | d| | d| t| fi |S )N	sort_keysindentr[   )r<   r   )xr}   r~   r[   rc   r   r   r   r   @  s   r   c                 C      |   S r   )tolistr(   r   r   r   
np_to_listL     r   c                 C   r   r   )itemr(   r   r   r   generic_to_itemP  r   r   	isoformat)dayssecondsmicroseconds)r,   realimag	numeratordenominatorhexamountcurrency)datetimedatetimer   tuplesetndarrayfloat16float32	frozensetcomplexr   r   UUIDr   r@   )key)r:   r7   )r   r   r   r   r   r   r   r   r   r   r   r   r   )r5   r6   c                 C      t |  S r   )parse_datetimer   vr   r   r   <lambda>      r   c                 C   r   r   )r   timetzr   r   r   r   r     r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 C   s   t | to	t| dS )N_fields)
isinstancer   hasattrrN   r   r   r   r     s    c                 C   s   t | jt| jt| dS )N)namefieldsvalues)rI   rJ   listr   r   r   r   r   _dump_namedtuple  s   r   c                 C   s   t | d | d }|| d  S )Nr   r   r   r   )valclsr   r   r   _load_namedtuple  s   r   r   F)r5   c                 C   s"   | j | j| jd d  d  d S )N   g      @i@B )r   r   r   )tdr   r   r   _timedelta_total_seconds  s
   r   r   c                 C   sD   ddl m}m} z	|| j | jW S  |y!   t| g d Y S w )z}Serialize standard (ISO-defined) currencies to currency code only,
    and non-standard (user-added) currencies in full.
    r   )CurrencyDoesNotExistget_currency)codenumericr   	countries)moneyedr   r   r   r-   )rN   r   r   r   r   r   _dump_currency  s   
r   c                 C   s2   ddl m} z|| dW S    tdi |  Y S )zDeserialize string values as standard currencies, but
    manually define fully-defined currencies (with code/name/numeric/countries).
    r   )r   )r   Nr   )r   r   r   )r   r   r   r   r   _load_currency  s
   r   r   c                 C   s   t di | S r.   )r   )r   r   r   r   _load_money  s   r   )NNT)Tr{   r|   )M__doc__numpynp
simplejsonrw   	threadinguuidcollectionsr   r   r   dateutil.parserr   r   decimalr   	fractionsr   	functoolsr   r	   operatorr
   r   sortedcontainersr   r   r   r   ImportError__all__r    r#   r`   localr   r   r!   r$   r-   r3   r4   r   rP   rQ   r   rU   rd   rf   rh   ru   r   r   r   r   r   r   r   r   r   strrC   r   r   asarrayr   r   r   r   r   rR   r   r   r   r   r   r   r   r   r   r   <module>   s   
>#


 %:





