o
    iq                     @   sj  U d dl Z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	 d dl
mZm
Z
mZ d dlmZmZ d dlmZmZ d dlmZmZmZmZmZmZmZ ejdkr[d dlmZ ndZd d	lmZmZmZm Z m!Z! d d
l"m#Z#m$Z$ d dl%m&Z&m'Z' d dl(m)Z)m*Z*m+Z+m,Z,m-Z- ejdkrd dlmZ ndZerd dl.m/Z/ edZ0ededZ1ededZ2ee3e4 ej	e3e4 e	e3e4 e5e5e4 e3e3e4 e6e6e4 e7e7e4df iZ8e9e:e:f e;d< eej	e	e5e3e6e7hZ<e9e4ee	e4 df f Z=de4de>fddZ?de4de@fddZAde4deBfddZCde4deDfddZEde4defdd ZFde4de
fd!d"ZGde4defd#d$ZHd%e:e1 d&ed'e4f d(ee4ge4f de1fd)d*ZId+e:e2 d,ee4 ed' B d(ee4ge4f de2fd-d.ZJe>e?e@eAeBeCeDeEeeFe
eGeeHiZKe9eef e;d/< d%e:e d,d'd0ee:e4gef dB d(ee4ge4f de7f
d1d2ZLd%ed3e9d4e9d0edB d(ee4ge4f f
d5d6ZMd&d'd%ed7ejNde4fd8d9ZOd%e:e0 d3e9e4ef de0fd:d;ZPd%e:e0 d&e	d' d4e9e4d<f d=ede0f
d>d?ZQd&ed'e	d' f d0eee4gef dB d(ee4ge4f fd@dAZR		dEd%ed,e	e4 e	d' B e=B d0ee:e4gef dB d(ee4ge4f dB fdBd=ZSd%ede7e@e>f fdCdDZTdS )F    N)CallableIterableSequence)datedatetime	timedelta)EnumFlag)partialreduce)TYPE_CHECKINGAnyLiteralTypeVarUnionget_args
get_origin)      )TypeAliasType)is_annotatedis_enum_flagis_nonetypeis_unionresolve)CoercionErrorValidationError)	FieldInfoget_field_infos)UNSETdefault_name_transformgrouper
is_builtinis_class_and_subclassTokenTE)boundF._implicit_iterable_type_mappingNestedCliArgssreturnc                 C   s*   |   } | dv r
dS | dv rdS ttd)N>   0fnnofalseF>   1tyyestrueT)target_type)lowerr   boolr,    r<   W/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/cyclopts/_convert.py_boolC   s   
r>   c                 C   sd   |   } | drt| dS | drt| dS | dr"t| dS d| v r.ttt| S t| S )N0x   0o   0b   .)r9   
startswithintroundfloatr;   r<   r<   r=   _intN   s   





rJ   c                 C   s   t | ddS )Nutf8)encoding)bytesr;   r<   r<   r=   _bytes_      rN   c                 C   s   t t| S N)	bytearrayrN   r;   r<   r<   r=   
_bytearrayc   rO   rR   c                 C   s
   t | S )zDParse a date string.

    Returns
    -------
    datetime.date
    )r   fromisoformatr;   r<   r<   r=   _dateg   s   
rT   c              
   C   s8   zt | W S  ty   t |  ddd Y S w )zLParse a datetime string.

    Returns
    -------
    datetime.datetime
     r&      )r   rS   
ValueErrorstripreplacer;   r<   r<   r=   	_datetimeq   s
   rZ   c                 C   s   d}|  drd}| dd } td| }|std|  d}|D ]S\}}}t|}|d	kr4||7 }q"|d
kr?||d 7 }q"|dkrJ||d 7 }q"|dkrU||d 7 }q"|dkr`||d 7 }q"|dkrk||d 7 }q"|dkru||d 7 }q"|r{| }t|dS )zParse a timedelta string.F-TrV   Nz((\d+\.\d+|\d+)([smhdwMy]))z!Could not parse duration string: r   r,   m<   hi  diQ wi:	 Mi ' r5   i3)seconds)rF   refindallrW   rI   r   )r,   negativematchesrb   _valueunitr<   r<   r=   
_timedelta   s8   


rj   type_tokenr%   name_transformc           	      C   sn   ddl m} t||}|r|jn|}||}| j D ]\}}|||kr)|  S qt|r2|| dd| d)zqMatch a token's value to an enum's member.

    Applies ``name_transform`` to both the value and the member.
    r   r$   Nrl   r8   )cyclopts.argumentr%   
isinstancerh   __members__itemsr   )	rk   rl   rm   r%   is_tokenrh   value_transformednamememberr<   r<   r=   get_enum_member   s   	
rw   	enum_typetokensc                    s"   t tj fdd|D  dS )a  Convert tokens to a Flag enum value.

    Parameters
    ----------
    enum_type : type[F]
        The Flag enum type to convert to.
    tokens : Iterable[str] | Iterable[Token]
        The tokens to convert. Can be member names or :class:`Token` objects.
    name_transform : Callable[[str], str] | None
        Function to transform names for comparison.

    Returns
    -------
    F
        The combined flag value.

    Raises
    ------
    CoercionError
        If a token is not a valid flag member.
    c                 3   s    | ]	}t  |V  qd S rP   )rw   ).0rl   rx   rm   r<   r=   	<genexpr>       z$convert_enum_flag.<locals>.<genexpr>r   )r   operatoror_)rx   ry   rm   r<   r{   r=   convert_enum_flag   s
   r   _converters	converterc          
         s<  t t||d tdd t| D }t| \}td|r]t| }|r5td dt| ddt|dkr@|d	 nt|d	krItnt	d
t fddt
|D S t|krqtd dt| dddd |D }t|fdd|D }dd |D }t fddt||ddD }	|	S )Nr   rm   c                 s   s    | ]	}|d ur|V  qdS ).Nr<   rz   xr<   r<   r=   r|      r}   z!_convert_tuple.<locals>.<genexpr>rV   z4Incorrect number of arguments: expected multiple of z	 but got rE   )msgr   z%A tuple must have 0 or 1 inner-types.c                 3   s*    | ]} d kr|d n|V  qdS )rV   r   Nr<   )rz   chunk)convertinner_token_count
inner_typer<   r=   r|     s
    
z(Incorrect number of arguments: expected c                 S   s   g | ]}t |d  qS )r   token_countr   r<   r<   r=   
<listcomp>  s    z"_convert_tuple.<locals>.<listcomp>c                    s"   g | ]} fd dt |D qS )c                    s   g | ]}t  qS r<   )next)rz   rg   itr<   r=   r     s    z-_convert_tuple.<locals>.<listcomp>.<listcomp>)range)rz   sizer   r<   r=   r     s   " c                 S   s$   g | ]}t |d kr|d n|qS )rV   r   )len)rz   elemr<   r<   r=   r     s   $ c                 3   s    | ]
\}} ||V  qd S rP   r<   )rz   r   argr   r<   r=   r|         F)strict)r
   _converttupler   r   maxr   r   strrW   r!   iterzip)
rk   r   rm   ry   inner_typesconsume_all	remainderargs_per_convertbatchedoutr<   )r   r   r   r   r=   _convert_tuple   s8   

 r   datafield_infosc                 C   s   ddl m} i }| D ]9\}}||v rE|| }	|	dur?t|jts?|t|	ttB r/t	
|	nt|	d}
t|j|
g||}n|	}|||< q| di |S )a  Convert JSON dict to dataclass with proper type conversion for fields.

    Parameters
    ----------
    type_ : Type
        The dataclass type to create.
    data : dict
        The JSON dictionary containing field values.
    field_infos : dict
        Field information from the dataclass.
    converter : Callable | None
        Optional converter function.
    name_transform : Callable[[str], str]
        Function to transform field names.

    Returns
    -------
    Instance of type_ with properly converted field values.
    r   r$   Nrh   r<   )cyclopts.tokenr%   rr   r#   hintr   rp   dictlistjsondumpsr   )rk   r   r   r   rm   r%   converted_data
field_name
field_inforh   rl   converted_valuer<   r<   r=   _convert_json  s   &r   errorc           
   	   C   s  | j  }t|dr|jnt|dr|jd nd}td|d }tt||d }||| }|dkr7d| }|t|k rA|d }|| }|dkrM|d7 }d}	t	d	|rXd
}	nt	d|rad}	nt	d|rjd}	nd|v rpd}	d|j
 d| dd|  d|j |	 	S )a  Create a helpful error message for JSON decode errors.

    Parameters
    ----------
    token : Token
        The token containing the invalid JSON.
    type_ : Type
        The target type we were trying to convert to.
    error : json.JSONDecodeError
        The JSON decode error that occurred.

    Returns
    -------
    str
        A formatted error message with context and hints.
    poscolnorV   r      z...r    z\bTrue\bz8
    Hint: Use lowercase 'true' instead of Python's Truez	\bFalse\bz:
    Hint: Use lowercase 'false' instead of Python's Falsez\bNone\bz.
    Hint: Use 'null' instead of Python's None'z9
    Hint: JSON requires double quotes, not single quoteszInvalid JSON for z:
    z
    rU   z^ )rh   rX   hasattrr   r   r   minr   rc   search__name__r   )
rl   rk   r   	value_str	error_possnippet_startsnippet_endsnippet
marker_posr   r<   r<   r=   !_create_json_decode_error_messageC  s,   
((r   c                    s   t | }|s| di |S g }i }| D ]\}}||}|r.|jtjkr.|||f q|||< qt|  |j	 fddd | dd |D i |S )a%  Instantiate a type with proper handling of parameter kinds.

    Respects POSITIONAL_ONLY, KEYWORD_ONLY, and POSITIONAL_OR_KEYWORD parameter kinds
    when constructing the object.

    This function is necessary because `inspect.signature().bind(**data)` has the same
    limitation we're solving: it cannot accept positional-only parameters as keyword
    arguments. For example, `def __init__(self, a, /, b)` requires `a` to be passed
    positionally, but when we have a dict `{"a": 1, "b": 2}`, we need to transform
    this into the call `type_(1, b=2)`.

    Parameters
    ----------
    type_ : type[T]
        The type to instantiate.
    data : dict[str, Any]
        Dictionary mapping field names to values.

    Returns
    -------
    T
        Instance of type_ constructed from data.
    c                    s     | d S )Nr   )index)r   field_names_orderr<   r=   <lambda>  s    z'instantiate_from_dict.<locals>.<lambda>)keyc                 s   s    | ]\}}|V  qd S rP   r<   )rz   rg   vr<   r<   r=   r|     s    z(instantiate_from_dict.<locals>.<genexpr>Nr<   )
r   rr   getkindr   POSITIONAL_ONLYappendr   keyssort)rk   r   r   pos_argskwargsr   rh   r   r<   r   r=   instantiate_from_dict{  s   

r   r   r   c                 C   s   d}i }| }|  D ]O\}}|j}t|tr"|| j}	|d7 }d}
n't|\}}|dkr8|||| }	|d7 }n||||||  }	||7 }|}
|	||< |
rQ n	|t|krY nq
|t|ksbJ t| |S )a  Convert tokens to a structured type with proper positional/keyword argument handling.

    Respects the parameter kind of each field:
    - POSITIONAL_ONLY: passed as positional argument
    - KEYWORD_ONLY or POSITIONAL_OR_KEYWORD: passed as keyword argument

    This correctly handles types with keyword-only fields (e.g., dataclasses with kw_only=True).

    Parameters
    ----------
    type_ : type[T]
        The target structured type to instantiate.
    token : Sequence[Token]
        The tokens to convert.
    field_infos : dict[str, FieldInfo]
        Field information for the structured type.
    convert : Callable
        Conversion function for nested types.

    Returns
    -------
    T
        Instance of type_ constructed from the tokens.
    r   rV   F)rr   r   r#   r   rh   r   r   r   )rk   rl   r   r   ir   r   r   r   rh   should_breaktokens_per_elementr   r<   r<   r=   _convert_structured_type  s0   



r   c                   s  ddl m  ddlm} d}t| r3ddlm} || \} jr,d}fdd}|}jr2j}ndtt	||d	tt
||d	}t| }t| | tu rZtttf |}	nE| tv rgt|  |}	n8|tjjtjjfv rtd
ksyJ td  |}	ntdurt| tr| j|}	n
t|rÈD ]}
t|
rqz|
|}	W  n ty   Y qw t|trtt|| dn|tu rd}t| D ](}z	t||}W n ty } z|}W Y d}~qd}~ww ||kr|}	 nq|r| |_ |tt|tr|d | d|| dn|t!u r4t| r'|| ||d}	nx|| g|R d|i}	nk|t"v rt#d \}}t|tsItd }|d
krft$ fdd|D rf|turf|}n|d
krxt%t&|g| ddi}n|}|fdd|D }	nt'| t(rt)| t|tr|n|g|}	n t'| t*rt|trt|du rt+| ||}	n|| |j,}	nt-| }t.| s|s-t| sJ z*|j/t0ur|j/}	n|du rt12| | |j,}	n|r|| |}	n|| |j,}	W n ty } z|j du r| |_ |j3du r||_3 d}~w ty,   t|| ddw t| r|j,4 5dr| turzt67|j,}t|tsPt8t9| ||||}	W nE t6j:yu } zt;|| |}t||| d|d}~w t8y   t|ts|g}t<| ||}	Y nw t|ts|g}t<| ||}	rzj=D ]}|| |	 qW |	S  t>tt8fy } zt?|j@r|j@d nd|	d|d}~ww |	S )zInner recursive conversion function for public ``convert``.

    Parameters
    ----------
    converter: Callable
    name_transform: Callable
    r   r$   )	ParameterFTc                    s    j sJ   | |fS rP   r   )t_rh   )cparamr<   r=   converter_with_token  s   
z&_convert.<locals>.converter_with_tokenNr   rV   rn   r   r   c                 3   s*    | ]}t | o|j d V  qdS ){N)rp   rh   rX   rF   )rz   r4   r$   r<   r=   r|   K  s   ( z_convert.<locals>.<genexpr>r   c                 3   s    | ]
} d  |V  qdS )r   Nr<   )rz   e)r   r   r<   r=   r|   T  r   r   )r   rl   r8   r   )exception_messagerh   )Aro   r%   cyclopts.parameterr   r   from_annotationr   rm   r
   r   r   r   r   r   r   r*   collectionsabcr   r   r   r   r   rp   	__value__r   r   	ExceptionrW   r   r   typer8   r   ITERABLE_TYPESr   anyr   r   r#   r	   r   r   rw   rh   r   r"   implicit_valuer   r   r   rl   rX   rF   r   loads	TypeErrorr   JSONDecodeErrorr   r   	validatorAssertionErrorr   args)rk   rl   r   rm   r   converter_needs_tokenr   convert_tupleorigin_typer   r4   last_coercion_errorchoiceresr   countrg   r   genr   r   r   r   r<   )r%   r   r   r   r=   r     s  


&




"

(
 r   c           
         s  ddl m  |s
tt|ts!t|d tr!t fdd|D }du r'ttt	dtt
d}ttu r?ttt}|pL}|tu rY|g|R  S |tv sc|tjju rh|S |tu rt|tsstztd W n ty   tY nw fdd	| D }t||di |S t|trtd
dt|rt||S t|dkrÈ|d S t\}}	|dkrׇfdd|D S t||kr|S td)a  Coerce variables into a specified type.

    Internally used to coercing string CLI tokens into python builtin types.
    Externally, may be useful in a custom converter.
    See Cyclopt's automatic coercion rules :doc:`/rules`.

    If ``type_`` **is not** iterable, then each element of ``tokens`` will be converted independently.
    If there is more than one element, then the return type will be a ``Tuple[type_, ...]``.
    If there is a single element, then the return type will be ``type_``.

    If ``type_`` **is** iterable, then all elements of ``tokens`` will be collated.

    Parameters
    ----------
    type_: Type
        A type hint/annotation to coerce ``*args`` into.
    tokens: Union[Sequence[str], NestedCliArgs]
        String tokens to coerce.
        Generally, either a list of strings, or a dictionary of list of strings (recursive).
        Each leaf in the dictionary tree should be a list of strings.
    converter: Optional[Callable[[Type, str], Any]]
        An optional function to convert tokens to the inner-most types.
        The converter should have signature:

        .. code-block:: python

            def converter(type_: type, value: str) -> Any:
                "Perform conversion of string token."

        This allows to use the :func:`convert` function to handle the the difficult task
        of traversing lists/tuples/unions/etc, while leaving the final conversion logic to
        the caller.
    name_transform: Optional[Callable[[str], str]]
        Currently only used for ``Enum`` type hints.
        A function that transforms enum names and CLI values into a normalized format.

        The function should have signature:

        .. code-block:: python

            def name_transform(s: str) -> str:
                "Perform name transform."

        where the returned value is the name to be used on the CLI.

        If ``None``, defaults to ``cyclopts.default_name_transform``.

    Returns
    -------
    Any
        Coerced version of input ``*args``.
    r   r$   c                 3   s    | ]
} t |d V  qdS )r   N)r   r   r$   r<   r=   r|     r   zconvert.<locals>.<genexpr>Nr   rV   c              	      s"   i | ]\}}|t | d qS )r   r   )rz   kr   )r   rm   
value_typer<   r=   
<dictcomp>  s    zconvert.<locals>.<dictcomp>z*Dictionary of tokens provided for unknown rE   c                    s   g | ]} |qS r<   r<   )rz   item)convert_privrk   r<   r=   r     s    zconvert.<locals>.<listcomp>zUnreachable?r<   )ro   r%   rW   rp   r   r   r   r    r
   r   r   r   r   r*   r   r   r   r   r   r   r   
IndexErrorrr   r   r   r   r   r   NotImplementedError)
rk   ry   r   rm   r   r   maybe_origin_typedict_convertedr   rg   r<   )r%   r   r   rm   rk   r   r=   r     sV   :



c                 C   s  t | } t| }|p| tu r#t| }|r!tdd |D d|v fS dS |p&| tu r+dS | tv s;|tv r=tt| dkr=dS t| rCdS |tv sM|t	j
ju r_tt| r_tt| d d dfS tdurmt| trmt| jS t| rt| }t|d }|d	d D ]}t|}||krtd
|d  d| q|S t| rdS t| }d\}}	| D ]}
|
j|
ju rd}	n|
jsqt|
j\}}||7 }|	|O }	q|sdS ||	fS )a  The number of tokens after a keyword the parameter should consume.

    Parameters
    ----------
    type_: Type
        A type hint/annotation to infer token_count from if not explicitly specified.

    Returns
    -------
    int
        Number of tokens to consume.
    bool
        If this is ``True`` and positional, consume all remaining tokens.
        The returned number of tokens constitutes a single element of the iterable-to-be-parsed.
    c                 s   s$    | ]}|d urt |d V  qdS ).r   Nr   r   r<   r<   r=   r|   (  s   " ztoken_count.<locals>.<genexpr>.)rV   T)r   Fr   TNrV   z=Cannot Union types that consume different numbers of tokens: rU   )rV   F)r   r   r   r   sumr:   r   r   r   r   r   r   r   r   rp   r   r   rW   r"   r   valuesr   VAR_POSITIONALrequiredr   )rk   r   r   sub_argstoken_count_target	sub_type_thisr   r   r   rh   
elem_countelem_consume_allr<   r<   r=   r     sV     

r   )NN)Ucollections.abcr   r   r~   rc   systypingr   r   r   r   r   r   enumr   r	   	functoolsr
   r   r   r   r   r   r   r   r   version_infor   cyclopts.annotationsr   r   r   r   r   cyclopts.exceptionsr   r   cyclopts.field_infor   r   cyclopts.utilsr   r    r!   r"   r#   ro   r%   r&   r'   r)   r   r   	frozensetsetr   r*   r   r   __annotations__r   r+   r:   r>   rG   rJ   rM   rN   rQ   rR   rT   rZ   rj   rw   r   r   r   r   r   r   r   r   r   r   r   r<   r<   r<   r=   <module>   s  
 $





%


#
+
.
"8-

@
 <
r