
    hC                        d dl Z d dl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mZmZ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 ee
gdf   Z ed      Zedee   d	ee   fd
       Zeddded	eee   gee   f   fd       Z	 d-dddeee      ded	eee   eee   gee   f   f   fdZeedddddfdeee   ef   dee
ef   deeg e
f   ef   dededee   dedee   de
d	e
fdZ defdZ!de"de
de
d	dfdZ#de"de
d ee
d!f   d	dfd"Z$de"de
d ee
d!f   d	dfd#Z%de"de
d ee
d!f   d	dfd$Z&de"de
d ee
d!f   d	dfd%Z'de"de
d ee
d!f   d	dfd&Z(de"de
d ee
d!f   d	dfd'Z)de"de
de*d	dfd(Z+d)ed	efd*Z,de
d	efd+Z-ee$ee%e.e&e/e'e0e(e1e)iZ2g d,Z3y).    N)_MISSING_TYPEMISSINGFieldfieldfields)wraps)AnyCallableDict
ForwardRefListLiteralOptionalTupleTypeTypeVarUnionget_args
get_originoverload   )#StrictDataclassClassValidationErrorStrictDataclassDefinitionError#StrictDataclassFieldValidationErrorTclsreturnc                      y N )r   s    \/var/www/html/axiom-chatbot/venv/lib/python3.12/site-packages/huggingface_hub/dataclasses.pystrictr"   !   s    %(    Faccept_kwargsr%   c                      y r   r    r$   s    r!   r"   r"   %   s    LOr#   c                \    dt         t           dt         t           ffd}|  ||       S |S )a  
    Decorator to add strict validation to a dataclass.

    This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools
    recognize the class as a dataclass.

    Can be used with or without arguments:
    - `@strict`
    - `@strict(accept_kwargs=True)`

    Args:
        cls:
            The class to convert to a strict dataclass.
        accept_kwargs (`bool`, *optional*):
            If True, allows arbitrary keyword arguments in `__init__`. Defaults to False.

    Returns:
        The enhanced dataclass with strict validation on field assignment.

    Example:
    ```py
    >>> from dataclasses import dataclass
    >>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field

    >>> @as_validated_field
    >>> def positive_int(value: int):
    ...     if not value >= 0:
    ...         raise ValueError(f"Value must be positive, got {value}")

    >>> @strict(accept_kwargs=True)
    ... @dataclass
    ... class User:
    ...     name: str
    ...     age: int = positive_int(default=10)

    # Initialize
    >>> User(name="John")
    User(name='John', age=10)

    # Extra kwargs are accepted
    >>> User(name="John", age=30, lastname="Doe")
    User(name='John', age=30, *lastname='Doe')

    # Invalid type => raises
    >>> User(name="John", age="30")
    huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
        TypeError: Field 'age' expected int, got str (value: '30')

    # Invalid value => raises
    >>> User(name="John", age=-1)
    huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
        ValueError: Value must be positive, got -1
    ```
    r   r   c           	          t         d      st        d j                   d      i }t               D ]  }g }|j	                  t        |             |j                  j                  d      }|Rt        |t              s|g}|D ])  }t        |      rt        d|j                   d| d       |j                  |       |||j                  <    | _         j                  dt        d	t         d
t        dd ffd}| _        r^ j"                  t%              dt        dd f fd       }| _         j&                  t%              dt         f fd       }| _        g }	t)               D ]  }
|
j+                  d      st-         |
      }t/        |      s-t1        t3        j4                  |      j6                        dk7  rt        d j                   d|
 d      |	j	                  |        |	 _        dt:        dd f fd}d|_        t         d      r0t-         j>                  dd      st        d j                   d      | _         j"                  t%              d fd       }tA         d|        S )N__dataclass_fields__zClass 'z.' must be a dataclass before applying @strict.	validatorzInvalid validator for field '': z.. Must be a callable taking a single argument.selfnamevaluer   c                     | j                   j                  |g       D ]  }	  ||         | ||       y# t        t        f$ r}t	        ||      |d}~ww xY w)z1Custom __setattr__ method for strict dataclasses.)r   causeN)__validators__get
ValueError	TypeErrorr   )r,   r-   r.   r*   eoriginal_setattrs        r!   __strict_setattr__z0strict.<locals>.wrap.<locals>.__strict_setattr__~   so     "0044T2> Z	Ze$Z T4/	 #I. Z=DPQRXYYZs   7AAAkwargsc                     t        	      D ch c]  }|j                   }}|j                         D ci c]  \  }}||v s|| }}} 
| fi | |j                         D ]  \  }}||vs| j                  ||        y c c}w c c}}w r   )r   r-   items__setattr__)r,   r8   fdataclass_fieldskvstandard_kwargsr-   r.   r   original_inits            r!   __init__z&strict.<locals>.wrap.<locals>.__init__   s     5;3K#@qAFF#@ #@4:LLN"\DAqaK[F[1a4"\"\ d6o6 $*<<> 6KD%#33((u56 $A"\s   BB
B
c                      |       }| j                   j                         D cg c]  \  }}|j                  vrd| d| }}}dj                  |      }|r|d d  d| dS |S c c}}w )N*=z, ))__dict__r:   r)   join)r,   standard_reprr>   r?   additional_kwargsadditional_reprr   original_reprs         r!   __repr__z&strict.<locals>.wrap.<locals>.__repr__   s     !.d 3 !% 3 3 5% 1 8 88 s!A5M%! % #')),="> GX-,-R/@Bj]jj%s    A*	validate_r   z' has a class validator 'z' that takes more than one argument. Class validators must take only 'self' as an argument. Methods starting with 'validate_' are considered to be class validators.c                     j                   D ]  }	  ||         y# t        t        f$ r}t        |j                  |      |d}~ww xY w)z%Run class validators on the instance.)r*   r0   N)__class_validators__r3   r4   r   __name__)r,   r*   r5   r   s      r!   validatez&strict.<locals>.wrap.<locals>.validate   sW     55 l	ldOl #I. l=	HZHZbcdjkkls   A	AA	TrS   "__is_defined_by_strict_decorator__Fz' already implements a method called 'validate'. This method name is reserved when using the @strict decorator on a dataclass. If you want to keep your own method, please rename it.c                 @     | g|i | j                  |        y)z*Run class validators after initialization.N)rS   )r,   argsr8   r   initial_inits      r!   init_with_validatez0strict.<locals>.wrap.<locals>.init_with_validate   s#     ///LLr#   rB   )r   N)!hasattrr   rR   r   append_create_type_validatormetadatar2   
isinstancelist_is_validatorr-   extendr1   r;   r	   strrB   r   rN   dir
startswithgetattrcallableleninspect	signature
parametersrQ   r   rT   rS   setattr)r   field_validatorsr<   
validatorscustom_validatorr*   r7   rB   rN   class_validatorsr-   methodrS   rX   rW   rA   rM   r6   r%   s   `             @@@@r!   wrapzstrict.<locals>.wrapc   s   s230#,,'UV 
 :< 	2AJ4Q78 zz~~k:+!"2D9(8'9$!1 I(3<;AFF83ykQ  A 
 !!"23'1QVV$	2 . ??
	0S 
	0 
	0C 
	0D 
	0 -LLM=!6 6 6 "6 $CL  LLM=!k# k "k  $CL H 	,D??;/S$'FF#7$$V,778A=4cll^+DTF K> > 
 ##F+	, $4 	l1 	l 	l 7;33
#3<<)MuU4cll^ ,N N    ||	|		 
	
 	Z!34
r#   )r   r   )r   r%   rp   s    ` r!   r"   r"   )   s8    tH$q' Hd1g HV 491T1r#   Tr*   defaultdefault_factoryinitreprhashcomparer\   r8   c                 `    t        | t              s| g} |i }| |d<   t        d|||||||d|S )a<  
    Create a dataclass field with a custom validator.

    Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator.

    Args:
        validator (`Callable` or `List[Callable]`):
            A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
            Can be a list of validators to apply multiple checks.
        **kwargs:
            Additional arguments to pass to `dataclasses.field()`.

    Returns:
        A field with the validator attached in metadata
    r*   rq   rr   rs   rt   ru   rv   r\   r    )r]   r^   r   )	r*   rq   rr   rs   rt   ru   rv   r\   r8   s	            r!   validated_fieldry      s[    4 i&K	%H[ 	'	 	 	r#   c                      t         t         dddddfdt        t        t        f   dt        t        g t        f   t        f   dt
        dt
        dt        t
           dt
        d	t        t           d
t        f fd}|S )a  
    Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator).

    Args:
        validator (`Callable`):
            A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
    TNrq   rr   rs   rt   ru   rv   r\   r8   c                 ,    t        f| ||||||d|S )Nrx   )ry   )	rq   rr   rs   rt   ru   rv   r\   r8   r*   s	           r!   _innerz"as_validated_field.<locals>._inner%  s9     

+

 

 
	
r#   )r   r   r	   r   r
   boolr   r   )r*   r|   s   ` r!   as_validated_fieldr~     s     .5CJ##'
sM)*
xC0-?@
 
 	

 tn
 
 4.
 
, Mr#   r-   r.   expected_typec                 $   t        |      }t        |      }|t        u ryt        j	                  |      x}r || ||       yt        |t              rt        | ||       yt        |t              st        |t              ryt        d|  d|       )z.Validate that 'value' matches 'expected_type'.NzUnsupported type for field 'r+   )r   r   r	   _BASIC_TYPE_VALIDATORSr2   r]   type_validate_simple_typer   ra   r4   )r-   r.   r   originrV   r*   s         r!   type_validatorr   >  s    &FM"D,008	8	8$t$	M4	(dE=9	M:	.*]C2P6tfCOPPr#   rV   .c                     g }|D ]  }	 t        | ||        y t        d|  dt	        |       d| ddj                  |             # t        $ r$}|j                  t        |             Y d}~kd}~ww xY w)z8Validate that value matches one of the types in a Union.NField 'z' with value z doesn't match any type in z
. Errors: z; )r   r4   rZ   ra   rt   rI   )r-   r.   rV   errorstr5   s         r!   _validate_unionr   O  s    F "	"4*" 
$}T%[M1LTFR\]a]f]fgm]n\op   	"MM#a&!!	"s   A	A5A00A5c                 4    ||vrt        d|  d| d|       y)zValidate Literal type.r   z' expected one of , got N)r4   )r-   r.   rV   s      r!   _validate_literalr   ^  s.    D'$'9$veWMNN r#   c           	         t        |t              s$t        d|  dt        |      j                         |d   }t        |      D ]  \  }}	 t        |  d| d||        y	# t        $ r}t        d| d|  d      |d	}~ww xY w)
zValidate List[T] type.r   z' expected a list, got r   []Invalid item at index z
 in list ''N)r]   r^   r4   r   rR   	enumerater   r-   r.   rV   	item_typeiitemr5   s          r!   _validate_listr   d  s    eT"'$'>tE{?S?S>TUVV QIU# R4	RdV1QCq>4;R  	R4QCz$qIJPQQ	Rs   A""	B+A>>Bc                 0   t        |t              s$t        d|  dt        |      j                         |\  }}|j                         D ])  \  }}	 t        |  d||       t        |  d|d||       + y# t        $ r}t        d|  d      |d}~ww xY w)	zValidate Dict[K, V] type.r   z' expected a dict, got z.keyr   r   zInvalid key or value in dict 'r   N)r]   dictr4   r   rR   r:   r   )r-   r.   rV   key_type
value_typer>   r?   r5   s           r!   _validate_dictr   r  s    eT"'$'>tE{?S?S>TUVV  Hj M1	MdV4=!X6dV1QE+Q
;M  	M<TF!DE1L	Ms   #A77	B BBc           
      f   t        |t              s$t        d|  dt        |      j                         t        |      dk(  r6|d   t        u r+t        |      D ]  \  }}	 t        |  d| d||d           yt        |      t        |      k7  r&t        d|  dt        |       dt        |             t        t        ||            D ]  \  }\  }}	 t        |  d| d||        y# t        $ r}t        d| d	|  d
      |d}~ww xY w# t        $ r}t        d| d	|  d
      |d}~ww xY w)zValidate Tuple type.r   z' expected a tuple, got    r   r   r   r   r   z in tuple 'r   Nz' expected a tuple of length r   )
r]   tupler4   r   rR   rf   Ellipsisr   r   zip)r-   r.   rV   r   r   r5   expecteds          r!   _validate_tupler     si   eU#'$'?U@T@T?UVWW 4yA~$q'X- ' 	WGAtW$q1~tT!W=	W 
Tc%j	 '$'DSYKvVYZ_V`Uabcc#,S-=#> 	WAhW$q1~tX>	W  W"8;tfA NOUVVW  W"8;tfA NOUVVWs0    C+D+	D4DD	D0D++D0c                     t        |t              s$t        d|  dt        |      j                         |d   }t        |      D ]  \  }}	 t        |  d||        y# t        $ r}t        d|  d      |d}~ww xY w)zValidate Set[T] type.r   z' expected a set, got r   z itemzInvalid item in set 'r   N)r]   setr4   r   rR   r   r   r   s          r!   _validate_setr     s    eS!'$'=d5k>R>R=STUU QIU# D4	DdV5>4;D  	D3D6;<!C	Ds   A	A=(A88A=c                     t        ||      s>t        d|  d|j                   dt        |      j                   dt	        |       d	      y)z&Validate simple type (int, str, etc.).r   z' expected r   z	 (value: rG   N)r]   r4   rR   r   rt   )r-   r.   r   s      r!   r   r     sX    e]+dV;}'='=&>fT%[EYEYDZZcdhindocppqr
 	
 ,r#   r   c                 $     dt         ddf fd}|S )z-Create a type validator function for a field.r.   r   Nc                 H    t        j                  | j                         y r   )r   r-   r   )r.   r   s    r!   r*   z)_create_type_validator.<locals>.validator  s    uzz5%**5r#   )r	   )r   r*   s   ` r!   r[   r[     s    6 6 6 r#   c                    t        |       syt        j                  |       }t        |j                  j                               }t        |      dk(  ry|d   j                  t        j                  j                  t        j                  j                  t        j                  j                  fvry|dd D ]+  }|j                  t        j                  j                  k(  s+ y y)zCheck if a function is a validator.

    A validator is a Callable that can be called with a single positional argument.
    The validator can have more arguments with default values.

    Basically, returns True if `validator(value)` is possible.
    Fr   r   NT)re   rg   rh   r^   ri   valuesrf   kind	ParameterPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYVAR_POSITIONALrq   empty)r*   rh   ri   	parameters       r!   r_   r_     s     I!!),Ii**1134J
:!!}//))((" 
 ^ 	 1 1 7 77 r#   )r"   ry   Validator_Tr   r   r   r   )4rg   dataclassesr   r   r   r   r   	functoolsr   typingr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r"   r}   ry   r~   ra   r   r   r   r   r   r   r   r   r   r[   r_   r^   r   r   r   r   __all__r    r#   r!   <module>r      sb    D D    "  ud{#CL 
 (Q (DG ( 
 ( 
$) OT OhQy$q'7I.J O 
 O "E2<AE2	$q'	E259E2
47Hd1gYQ/001E2T *1?F#(T+&34(3%&( 8BG,m;<( 	(
 ( 4.( ( tn( ( 	(V+ DQ QS Q Q Q"# c sCx T OC O O5c? Ot OR RS Rc3h RD RM MS Mc3h MD MW# Wc WsCx WT W.D DC DuS#X D4 D
 
C 
 
 
% K S T 8 
?..	? r#   