
    wiC                        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,Z3dS ).    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                     d S N )r   s    s/var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/huggingface_hub/dataclasses.pystrictr"   !   s    %(S    Faccept_kwargsr%   c                     d S r   r    r$   s    r!   r"   r"   %   s    LOCr#   c                v    dt           t                   dt           t                   ffd}|  ||           n|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           	      z    t           d          st          d j         d          i }t                     D ]}g }|                    t          |                     |j                            d          }|\t          |t                    s|g}|D ],}t          |          st          d|j         d| d          -|                    |           |||j        <   | _         j        dt          d	t           d
t          dd ffd}| _        rd j        t%                    dt          dd f fd            }| _         j        t%                    dt           f fd            }| _        g }	t)                     D ]}
|
                    d          st-           |
          }t/          |          s8t1          t3          j        |          j                  dk    rt          d j         d|
 d          |	                    |           |	 _        dt:          dd f fd}d|_        t           d          r.t-           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                             |g           D ]9}	  ||           # t          t          f$ r}t	          ||          |d}~ww xY w | ||           dS )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__~   s     "044T2>> Z Z	ZIe$$$$"I. Z Z Z=DPQRRRXYYZ T4/////s   ,AAAkwargsc                     d t                    D             fd|                                D             } | fi | |                                D ]\  }}|vr|                     ||            d S )Nc                     h | ]	}|j         
S r    )r-   ).0fs     r!   	<setcomp>z9strict.<locals>.wrap.<locals>.__init__.<locals>.<setcomp>   s    #@#@#@qAF#@#@#@r#   c                 $    i | ]\  }}|v 	||S r    r    )r;   kvdataclass_fieldss      r!   
<dictcomp>z:strict.<locals>.wrap.<locals>.__init__.<locals>.<dictcomp>   s*    "\"\"\DAqaK[F[F[1aF[F[F[r#   )r   items__setattr__)r,   r8   standard_kwargsr-   r.   rA   r   original_inits        @r!   __init__z&strict.<locals>.wrap.<locals>.__init__   s     $A#@F3KK#@#@#@ "\"\"\"\FLLNN"\"\"\ d66o666 $*<<>> 6 6KD%#333((u5556 6r#   c                      |           }fd| j                                         D             }d                    |          }|r|d d          d| dn|S )Nc                 8    g | ]\  }}|j         vd | d|S )*=)r)   )r;   r?   r@   r   s      r!   
<listcomp>z:strict.<locals>.wrap.<locals>.__repr__.<locals>.<listcomp>   sC     % % % 1 888 "MMAMM888r#   z, ))__dict__rC   join)r,   standard_repradditional_kwargsadditional_reprr   original_reprs       r!   __repr__z&strict.<locals>.wrap.<locals>.__repr__   s     !.d 3 3% % % % !% 3 3 5 5% % %! #')),=">"> GXj-,BBBBBB]jjr#   	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 ]>}	  ||            # t          t          f$ r}t          |j        |          |d}~ww xY wdS )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   sz     5 l l	lIdOOOO"I. l l l=	HZbcdddjkkll ls   AA  ATrZ   "__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                 J     | g|R i |                      |            dS )z*Run class validators after initialization.N)rZ   )r,   argsr8   r   initial_inits      r!   init_with_validatez0strict.<locals>.wrap.<locals>.init_with_validate   s=     L///////LLr#   rG   )r   N)!hasattrr   rY   r   append_create_type_validatormetadatar2   
isinstancelist_is_validatorr-   extendr1   rD   r	   strrG   r   rU   dir
startswithgetattrcallableleninspect	signature
parametersrX   r   r[   rZ   setattr)r   field_validatorsr<   
validatorscustom_validatorr*   r7   rG   rU   class_validatorsr-   methodrZ   r_   r^   rF   rT   r6   r%   s   `             @@@@r!   wrapzstrict.<locals>.wrapc   s   s233 	0V#,VVV  
 :< 	2 	2AJ4Q77888 z~~k::+!"2D99 :(8'9$!1  I(33 < AAF  A  Ay  A  A  A   !!"2333'1QV$$- ?
	0S 
	0 
	0C 
	0D 
	0 
	0 
	0 
	0 
	0 
	0 - (	$LM=!!6 6 6 6 6 6 6 6 "!6 $CL  LM=!!k# k k k k k k "!k  $CL HH 	, 	,D??;// S$''FF## 7$V,,788A==4>cl > >T > > >  
 ##F++++#3 	l1 	l 	l 	l 	l 	l 	l 	l 7;33
## 	3<)MuUU 4Ncl N N N     |	|			 	 	 	 	 	 
		
 	Z!3444
r#   )r   r   )r   r%   rw   s    ` r!   r"   r"   )   sY    tH$q' Hd1g H H H H H HV 44999T1r#   Tr*   defaultdefault_factoryinitreprhashcomparerc   r8   c                 l    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
    Nr*   rx   ry   rz   r{   r|   r}   rc   r    )rd   re   r   )	r*   rx   ry   rz   r{   r|   r}   rc   r8   s	            r!   validated_fieldr      sm    4 i&&  K	%H[ 	'	 	 	 	 	r#   c                 6    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.
    TNrx   ry   rz   r{   r|   r}   rc   r8   c                 .    t          f| ||||||d|S )Nr   )r   )	rx   ry   rz   r{   r|   r}   rc   r8   r*   s	           r!   _innerz"as_validated_field.<locals>._inner%  sC     

+

 

 

 

 
	
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dS t                              |          x}r || ||           dS t          |t                    rt          | ||           dS t          |t                    st          |t                    rdS t          d|  d|           )z.Validate that 'value' matches 'expected_type'.NzUnsupported type for field 'r+   )r   r   r	   _BASIC_TYPE_VALIDATORSr2   rd   type_validate_simple_typer   rh   r4   )r-   r.   r   originr]   r*   s         r!   type_validatorr   >  s    &&FM""D,0088	8 Q	$t$$$$$	M4	(	( QdE=99999	M:	.	. Q*]C2P2P QOtOOOOPPPr#   r]   .c                     g }|D ]O}	 t          | ||            dS # t          $ r,}|                    t          |                     Y d}~Hd}~ww xY wt          d|  dt	          |           d| dd                    |                     )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   ra   rh   r{   rP   )r-   r.   r]   errorstr5   s         r!   _validate_unionr   O  s    F " "	"4***FF 	" 	" 	"MM#a&&!!!!!!!!	" p$ppT%[[ppTpp]a]f]fgm]n]npp  s   
A"AAc                 >    ||vrt          d|  d| d|           dS )zValidate Literal type.r   z' expected one of , got N)r4   )r-   r.   r]   s      r!   _validate_literalr   ^  s<    DM$MM$MMeMMNNN r#   c           	      :   t          |t                    s't          d|  dt          |          j                   |d         }t          |          D ]F\  }}	 t          |  d| d||           # t          $ r}t          d| d|  d          |d	}~ww xY wd	S )
zValidate List[T] type.r   z' expected a list, got r   []Invalid item at index z
 in list ''N)rd   re   r4   r   rY   	enumerater   r-   r.   r]   	item_typeiitemr5   s          r!   _validate_listr   d  s    eT"" WU$UUtE{{?SUUVVV QIU## R R4	Rd>>Q>>>4;;;; 	R 	R 	RIQII$IIIJJPQQ	RR Rs   A22
B<BBc                 `   t          |t                    s't          d|  dt          |          j                   |\  }}|                                D ]W\  }}	 t          |  d||           t          |  d|d||           2# t          $ r}t          d|  d          |d}~ww xY wdS )	zValidate Dict[K, V] type.r   z' expected a dict, got z.keyr   r   zInvalid key or value in dict 'r   N)rd   dictr4   r   rY   rC   r   )r-   r.   r]   key_type
value_typer?   r@   r5   s           r!   _validate_dictr   r  s    eT"" WU$UUtE{{?SUUVVV  Hj M M1	Md===!X666d++Q+++Q
;;;; 	M 	M 	MDTDDDEE1L	M	M Ms   +B
B+B&&B+c           
         t          |t                    s't          d|  dt          |          j                   t          |          dk    rm|d         t          u r^t          |          D ]L\  }}	 t          |  d| d||d                    $# t          $ r}t          d| d	|  d
          |d}~ww xY wdS t          |          t          |          k    r2t          d|  dt          |           dt          |                     t          t          ||                    D ]I\  }\  }}	 t          |  d| d||           !# t          $ r}t          d| d	|  d
          |d}~ww xY wdS )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   )
rd   tupler4   r   rY   rm   Ellipsisr   r   zip)r-   r.   r]   r   r   r5   expecteds          r!   _validate_tupler     s   eU## XV$VVU@TVVWWW 4yyA~~$q'X-- '' 	W 	WGAtW$~~~~~tT!W==== W W W N N Nt N N NOOUVVW	W 	W 
Tc%jj	 	 b$bbSYYbbVYZ_V`V`bbccc#,S-=-=#>#> 	W 	WAhW$~~~~~tX>>>> W W W N N Nt N N NOOUVVW	W 	Ws0   4B
B8B33B85E
E3E..E3c                 .   t          |t                    s't          d|  dt          |          j                   |d         }t          |          D ]@\  }}	 t          |  d||           # t          $ r}t          d|  d          |d}~ww xY wdS )zValidate Set[T] type.r   z' expected a set, got r   z itemzInvalid item in set 'r   N)rd   setr4   r   rY   r   r   r   s          r!   _validate_setr     s    eS!! VT$TTd5kk>RTTUUU QIU## D D4	Dd>>>4;;;; 	D 	D 	D;D;;;<<!C	DD Ds   A//
B9BBc                     t          ||          s@t          d|  d|j         dt          |          j         dt	          |           d	          dS )z&Validate simple type (int, str, etc.).r   z' expected r   z	 (value: rN   N)rd   r4   rY   r   r{   )r-   r.   r   s      r!   r   r     sl    e]++ 
rdrr}'=rrT%[[EYrrdhindodorrr
 
 	

 
r#   r   c                 &     dt           ddf fd}|S )z-Create a type validator function for a field.r.   r   Nc                 >    t          j        | j                   d S r   )r   r-   r   )r.   r   s    r!   r*   z)_create_type_validator.<locals>.validator  s    uz5%*55555r#   )r	   )r   r*   s   ` r!   rb   rb     s7    6 6 6 6 6 6 6 6 r#   c                    t          |           sdS t          j        |           }t          |j                                                  }t          |          dk    rdS |d         j        t          j        j	        t          j        j
        t          j        j        fvrdS |dd         D ]}|j        t          j        j        k    r dS  dS )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)rl   rn   ro   re   rp   valuesrm   kind	ParameterPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYVAR_POSITIONALrx   empty)r*   ro   rp   	parameters       r!   rf   rf     s     I u!),,Ii*113344J
:!u!}/)("  
 u^  	 1 77755 84r#   )r"   r   Validator_Tr   r   r   r   )4rn   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   r   r   rh   r   r   r   r   r   r   r   r   r   rb   rf   re   r   r   r   r   __all__r    r#   r!   <module>r      s`    D D D D D D D D D D D D D D                                     "          ud{#GCLL 
 (Q (DG ( ( ( 
 ( 
$) O O OT OhQy$q'7I.J O O O 
 O "E2<AE2 E2 E2	$q'	E259E2
47Hd1gYQ/001E2 E2 E2 E2T *1?F#( (T+&34(3%&( 8BG,m;<( 	(
 ( 4.( ( tn( ( 	( ( ( (V+    DQ QS Q Q Q Q Q Q"# c sCx T    OC O O5c? Ot O O O OR RS Rc3h RD R R R RM MS Mc3h MD M M M MW# Wc WsCx WT W W W W.D DC DuS#X D4 D D D D
 
C 
 
 
 
 
 
% K    S T    8 
?..	?   r#   