
    o i6W                        d dl Z d dlmZmZmZmZ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mZmZmZmZmZ 	 d dlmZmZ n:# e$ r2 	 d dlmZmZ n%# e$ r  eddi           Z eddi           ZY nw xY wY nw xY wd	d
lmZmZm Z  eegdf         Z! ed          Z" ede#e$ef                   Z% e&            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(dee%         de#ddfdZ*e	dee%         defd            Z+dee%         de#e$e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*Z0d'e$d(ed+e1ed,f         ddfd-Z2d'e$d(ed+e1ed,f         ddfd.Z3d'e$d(ed+e1ed,f         ddfd/Z4d'e$d(ed+e1ed,f         ddfd0Z5d'e$d(ed+e1ed,f         ddfd1Z6d'e$d(ed+e1ed,f         ddfd2Z7d'e$d(ed)eddfd3Z8d4ede!fd5Z9dede)fd6Z:d7ede)fd8Z;ee2ee3e-e4e#e5e1e6e<e7iZ=g d9Z>dS );    N)_MISSING_TYPEMISSINGFieldfieldfieldsmake_dataclass)	lru_cachewraps)	AnnotatedAnyCallable
ForwardRefLiteralOptionalTypeTypeVarUnionget_args
get_originoverload)NotRequiredRequiredr    r      )#StrictDataclassClassValidationErrorStrictDataclassDefinitionError#StrictDataclassFieldValidationErrorTTypedDictType)boundclsreturnc                     d S Nr   )r!   s    [/var/www/html/auto_sub_bot/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&   3   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   )r0   r1   r2   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   )r1   ).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__)r0   r<   standard_kwargsr1   r2   rE   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?   rC   rD   r!   s      r%   
<listcomp>z:strict.<locals>.wrap.<locals>.__repr__.<locals>.<listcomp>   sC     % % % 1 888 "MMAMM888r'   z, ))__dict__rG   join)r0   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.   r4   N)__class_validators__r7   r8   r   __name__)r0   r.   r9   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Tr^   "__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)r^   )r0   argsr<   r!   initial_inits      r%   init_with_validatez0strict.<locals>.wrap.<locals>.init_with_validate   s=     L///////LLr'   rK   )r"   N)!hasattrr   r]   r   append_create_type_validatormetadatar6   
isinstancelist_is_validatorr1   extendr5   rH   r   strrK   r
   rY   dir
startswithgetattrcallableleninspect	signature
parametersr\   r   r_   r^   setattr)r!   field_validatorsr@   
validatorscustom_validatorr.   r;   rK   rY   class_validatorsr1   methodr^   rc   rb   rJ   rX   r:   r)   s   `             @@@@r%   wrapzstrict.<locals>.wrapq   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)   r{   s    ` r%   r&   r&   7   sY    tH$q' Hd1g H H H H H HV 44999T1r'   schemadatac                 4    t          |           } |di | dS )a  
    Validate that a dictionary conforms to the types defined in a TypedDict class.

    Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator.

    Args:
        schema (`type[TypedDictType]`):
            The TypedDict class defining the expected structure and types.
        data (`dict`):
            The dictionary to validate.

    Raises:
        `StrictDataclassFieldValidationError`:
            If any field in the dictionary does not conform to the expected type.

    Example:
    ```py
    >>> from typing import Annotated, TypedDict
    >>> from huggingface_hub.dataclasses import validate_typed_dict

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

    >>> class User(TypedDict):
    ...     name: str
    ...     age: Annotated[int, positive_int]

    >>> # Valid data
    >>> validate_typed_dict(User, {"name": "John", "age": 30})

    >>> # Invalid type for age
    >>> validate_typed_dict(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 for age
    >>> validate_typed_dict(User, {"name": "John", "age": -1})
    huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
        ValueError: Value must be positive, got -1
    ```
    Nr   )!_build_strict_cls_from_typed_dict)r|   r}   
strict_clss      r%   validate_typed_dictr      s0    X 36::J Jr'   c                    t          |           }t          | dd          s|                                D ]\  }}t          |          }|t          u r\t          |          ^}}t          |          st          |         }t          t          |gt          |          z                      ||<   yt          |          st          |         ||<   g }|                                D ]\  }}t          |          t          u rAt          |          ^}} |j
        ||t          t          d|d         i          f           \ |j
        ||t          t                    f           t          t          | j        |                    S )N	__total__Tr.   r   )defaultrg   )r   )_get_typed_dict_annotationsro   rG   r   r   r   _is_required_or_notrequiredr   tupleri   re   r   _TYPED_DICT_DEFAULT_VALUEr&   r   r]   )r|   
type_hintskeyr2   originbasemetar   s           r%   r   r   1  s    -V44J 6;-- 
5$**,, 		5 		5JC&&F""&uoot2488 -&t,D"+E4&4::2E,F,F"G
3077 5"-e"4
3 F &&(( R R
Ue	))"5//KD4FM3e4MYdfjklfmXn&o&o&opqqqqFM3u5N'O'O'OPQQQQ .&99:::r'   c                     	 ddl }|                    |           S # t          $ r: d | j                            di                                           D             cY S w xY w)z0Extract type annotations from a TypedDict class.r   Nc                 <    i | ]\  }}|||nt          d           S r$   )type)r?   r1   r2   s      r%   rF   z/_get_typed_dict_annotations.<locals>.<dictcomp>X  s?     
 
 
 e 5,%%$t**
 
 
r'   __annotations__)annotationlibget_annotationsImportErrorrS   r6   rG   )r|   r   s     r%   r   r   P  s    
,,V444 
 
 

 
  &223DbIIOOQQ	
 
 
 	
 	
 	

s    AAATr.   r   default_factoryinitreprhashcomparerg   r<   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.   r   r   r   r   r   r   rg   r   )rh   ri   r   )	r.   r   r   r   r   r   r   rg   r<   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.
    TNr   r   r   r   r   r   rg   r<   c                 .    t          f| ||||||d|S )Nr   )r   )	r   r   r   r   r   r   rg   r<   r.   s	           r%   _innerz"as_validated_field.<locals>._inner  sC     

+

 

 

 

 
	
r'   )r   r   r   r   r   boolr   dict)r.   r   s   ` r%   as_validated_fieldr     s     .5CJ##'
 
sM)*
xC0-?@
 
 	

 tn
 
 4.
 
 
 
 
 
 
, Mr'   r1   r2   expected_typec                 R   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          u r5|t          u rt          d|  d          t          | ||d                    dS |t          u r$|t          u rdS t          | ||d                    dS t          d|  d|           )z.Validate that 'value' matches 'expected_type'.NField 'z' is required but missing.r   zUnsupported type for field 'r/   )r   r   r   _BASIC_TYPE_VALIDATORSr6   rh   r   _validate_simple_typer   rl   r   r   r8   type_validatorr   )r1   r2   r   r   ra   r.   s         r%   r   r     s[   &&FM""D,0088	8 Q	$t$$$$$	M4	(	( QdE=99999	M:	.	. Q*]C2P2P Q	8		---FdFFFGGGtUDG,,,,,	;		---FtUDG,,,,,OtOOOOPPPr'   ra   .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.Nr   z' with value z doesn't match any type in z
. Errors: z; )r   r8   re   rl   r   rT   )r1   r2   ra   errorstr9   s         r%   _validate_unionr     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)r8   )r1   r2   ra   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)rh   ri   r8   r   r]   	enumerater   r1   r2   ra   	item_typeiitemr9   s          r%   _validate_listr     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)rh   r   r8   r   r]   rG   r   )r1   r2   ra   key_type
value_typerC   rD   r9   s           r%   _validate_dictr     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   )
rh   r   r8   r   r]   rq   Ellipsisr   r   zip)r1   r2   ra   r   r   r9   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)rh   setr8   r   r]   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: rR   N)rh   r8   r]   r   r   )r1   r2   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.r2   r"   Nc                 >    t          j        | j                   d S r$   )r   r1   r   )r2   r   s    r%   r.   z)_create_type_validator.<locals>.validator)  s    uz5%*55555r'   )r   )r   r.   s   ` r%   rf   rf   %  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)rp   rr   rs   ri   rt   valuesrq   kind	ParameterPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYVAR_POSITIONALr   empty)r.   rs   rt   	parameters       r%   rj   rj   /  s     I u!),,Ii*113344J
:!u!}/)("  
 u^  	 1 77755 84r'   	type_hintc                 \    | t           t          fv pt          |           t           t          fv S )z2Helper to check if a type is Required/NotRequired.)r   r   r   )r   s    r%   r   r   J  s*    ;//eJy4I4IhXcMd4der'   )r&   r   r   Validator_Tr   r   r   r$   )?rr   dataclassesr   r   r   r   r   r   	functoolsr	   r
   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r   r   r   r   r   r   rl   r   objectr   r&   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   rf   rj   r   r   r   __all__r   r'   r%   <module>r      s    T T T T T T T T T T T T T T T T & & & & & & & &                            
2,,,,,,,,, 2 2 22;;;;;;;;; 2 2 24
B++d="b112	2          ud{#GCLLtCH~>>>"FHH  
 (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2P/] 3 /4 /D / / / /d ;d=.A ;d ; ; ; ;<
](; 
S#X 
 
 
 
$ *1?F#( (T+&34(3%&( 8BG,m;<( 	(
 ( 4.( ( tn( ( 	( ( ( (V+    DQ QS Q Q Q Q Q Q2# 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    6f3 f4 f f f f 
?..	?   s5   A A:	AA:A41A:3A44A:9A: