a
    Ofz                  	   @  s  d Z ddlm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
 ddlmZ ddlmZ ddlmZmZmZmZ ddlZddlmZmZ dd	lmZmZ d
dlmZmZ d
dlmZ d
dlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z= ddl>m?Z? ej@rd
dlAmBZC d
dlAmDZDmEZE d
dlAmFZG d
dlHmIZI neZJeK ZCeK ZGeKjLZMG dd deNZOed eCeGfd!G d"d# d#e
ZPd$d%d&d'd(d)ZQd*d+d,d-d.d/ZRd*d+d0d0d1d2d3d4ZSd5d+d&d6d7d8ZTd5d%d9d:d;ZUd5d+d<d*d&d=d>d?ZVd dd@d5dAd<dBdCdDdBdEdFdGZWd5d&d9dHdIZXG dJdK dKZYG dLdM dMZZdCdCdNdOdPZ[dCdCdNdQdRZ\d+dSdTdUZ]dS )Vz"Private logic for creating models.    )annotationsN)ABCMeta)partial)FunctionType)AnyCallableGenericNoReturn)PydanticUndefinedSchemaSerializer)dataclass_transform
deprecated   )PydanticUndefinedAnnotationPydanticUserError)create_schema_validator)GenericBeforeBaseModelWarningPydanticDeprecatedSince20   )ConfigWrapper)DecoratorInfosPydanticDescriptorProxyget_attribute_from_basesunwrap_wrapped_function)collect_model_fieldsis_valid_field_nameis_valid_privateattr_name)GenerateSchema)PydanticGenericMetadataget_model_typevars_map)set_model_mocks)CallbackGetCoreSchemaHandler)generate_pydantic_signature)get_cls_types_namespaceis_annotatedis_classvarparent_frame_namespace)ClassAttributeSafeGetItemProxy)ValidateCallWrapper)Field)	FieldInfoModelPrivateAttr)PrivateAttr	BaseModelc                      s*   e Zd ZdZdddd fddZ  ZS )_ModelNamespaceDictz{A dictionary subclass that intercepts attribute setting on model classes and
    warns about overriding of decorators.
    strobjectNone)kvreturnc                   sL   |  |d }|r>||ur>t|tr>td| d|jj d t ||S )N`z"` overrides an existing Pydantic `z` decorator)	get
isinstancer   warningswarnZdecorator_infoZdecorator_reprsuper__setitem__)selfr4   r5   existing	__class__ _/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pydantic/_internal/_model_construction.pyr=   6   s    z_ModelNamespaceDict.__setitem__)__name__
__module____qualname____doc__r=   __classcell__rB   rB   r@   rC   r0   1   s   r0   T)kw_only_defaultfield_specifiersc                
      s   e Zd Zd%ddddddd	d
d fddZejs@dd	dddZed	d	ddddZd	dd fddZ	e
dddddZeedddddd d!Zd"d fd#d$Z  ZS )&ModelMetaclassNTr1   tuple[type[Any], ...]dict[str, Any]zPydanticGenericMetadata | Nonebool
str | Noner   type)cls_namebases	namespace__pydantic_generic_metadata__#__pydantic_reset_parent_namespace___create_model_modulekwargsr6   c                   sl  |rN|  |\}}	}
t|||}|j|d< t||j|	|}|sF|
rt||  durxdddd fdd}||d	< nt|d	< |	|d
< i |
||d< t j	| |||fi |}ddl
m} |j}t|v r|t||k rtjtddd t|jdd |_|j|ju rdnd	|_t||_|r8||_n<t|di ddt|ddp\rfrftfddD sfddlm} tfddD }|v r|vrd dd |D }|j! d| d|j! d| d }np| }d d!d |D }d"| d#}d$| d%}t|vr^d d&d |D |g }|d'|j! d(| d)7 }t"|ddd*|_d|_#|$ D ]\}}|%|| q|rt&t' |_(t|d+d}t)|t*rt+|}t,||}t-|||| |j.r d,|vr t/|| t0|||d||d- d.d/ |jj1$ D |_2t3| t||j4f i | |S t j	| |||fi |S dS )0a  Metaclass for creating Pydantic models.

        Args:
            cls_name: The name of the class to be created.
            bases: The base classes of the class to be created.
            namespace: The attribute dictionary of the class to be created.
            __pydantic_generic_metadata__: Metadata for generic models.
            __pydantic_reset_parent_namespace__: Reset parent namespace.
            _create_model_module: The module of the class to be created, if created by `create_model`.
            **kwargs: Catch-all for any other keyword arguments.

        Returns:
            The new class created by the metaclass.
        model_configNr/   r   r3   r>   contextr6   c                  s   t | |  | | dS )zWe need to both initialize private attributes and call the user-defined model_post_init
                        method.
                        N)init_private_attributes)r>   rZ   )original_model_post_initrB   rC   wrapped_model_post_inith   s    
z7ModelMetaclass.__new__.<locals>.wrapped_model_post_initmodel_post_init__class_vars____private_attributes__r   r.   zClasses should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) for pydantic generics to work properly.
stacklevelZ__pydantic_base_init__FrT   
parametersrB   __parameters__c                 3  s   | ]}| v V  qd S NrB   .0x)rc   rB   rC   	<genexpr>       z)ModelMetaclass.__new__.<locals>.<genexpr>)RootModelRootTypec                 3  s   | ]}| vr|V  qd S re   rB   rf   )parent_parametersrB   rC   ri      rj   z, c                 S  s   g | ]
}|j qS rB   rD   rf   rB   rB   rC   
<listcomp>   rj   z*ModelMetaclass.__new__.<locals>.<listcomp>zS is a subclass of `RootModel`, but does not include the generic type identifier(s) zL in its parameters. You should parametrize RootModel directly, e.g., `class z(RootModel[z	]): ...`.c                 S  s   g | ]}t |qS rB   )r1   rf   rB   rB   rC   rn      rj   ztyping.Generic[]zJAll parameters must be present on typing.Generic; you should inherit from .c                 S  s   g | ]
}|j qS rB   rm   rf   rB   rB   rC   rn      rj   z- Note: `typing.Generic` must go last: `class (z): ...`))originargsrc   __pydantic_parent_namespace____hash__)raise_errorstypes_namespacecreate_model_modulec                 S  s   i | ]\}}||j qS rB   )info)rg   r4   r5   rB   rB   rC   
<dictcomp>   rj   z*ModelMetaclass.__new__.<locals>.<dictcomp>)5_collect_bases_datar   Z	for_modelZconfig_dictinspect_namespaceignored_typesget_model_post_initr[   r<   __new__mainr/   __mro__r   indexr:   r;   r   getattr__init__Z__pydantic_custom_init__r^   Z__pydantic_post_init__r   buildZ__pydantic_decorators__rT   r8   allZ
root_modelrk   tuplejoinrD   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr&   rt   r9   dictunpack_lenient_weakvaluedictr#   set_model_fieldsfrozenset_default_hash_funccomplete_model_classZcomputed_fieldsmodel_computed_fieldsset_deprecated_descriptorsZ__pydantic_init_subclass__)mcsrQ   rR   rS   rT   rU   rV   rW   Zbase_field_names
class_varsZbase_private_attributesconfig_wrapperprivate_attributesr]   clsr/   mrork   Zmissing_parametersZparameters_strerror_messageZcombined_parametersZgeneric_type_labelZ	bases_strnameobjZparent_namespacerw   r@   )r\   rc   rl   rC   r   @   s    




$


zModelMetaclass.__new__)itemr6   c                 C  s,   | j d}|r ||v r || S t|dS )zNThis is necessary to keep attribute access working for class attribute access.r`   N)__dict__r8   AttributeError)r>   r   r   rB   rB   rC   __getattr__   s    zModelMetaclass.__getattr__zdict[str, object])rs   rW   r6   c                 O  s   t  S re   )r0   )r   rs   rW   rB   rB   rC   __prepare__   s    zModelMetaclass.__prepare__)instancer6   c                   s   t |dot |S )zsAvoid calling ABC _abc_subclasscheck unless we're pretty sure.

        See #3829 and python/cpython#92810
        __pydantic_validator__)hasattrr<   __instancecheck__)r>   r   r@   rB   rC   r      s    z ModelMetaclass.__instancecheck__z6tuple[set[str], set[str], dict[str, ModelPrivateAttr]])rR   r6   c                 C  sp   ddl m} t }t }i }| D ]D}t||r ||ur |t|di   ||j ||j q |||fS )Nr   r.   model_fields)	r   r/   set
issubclassupdater   keysr_   r`   )rR   r/   field_namesr   r   baserB   rB   rC   r{      s    z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categoryzdict[str, FieldInfo]r6   c                 C  s   t dt | jS )Nr   )r:   r;   r   r   r>   rB   rB   rC   
__fields__	  s    zModelMetaclass.__fields__z	list[str]c                   s$   t t  }d|v r |d |S )Nr   )listr<   __dir__remove)r>   
attributesr@   rB   rC   r     s    
zModelMetaclass.__dir__)NTN)rD   rE   rF   r   typingTYPE_CHECKINGr   classmethodr   r   staticmethodr{   propertyr   r   r   rH   rB   rB   r@   rC   rK   >   s       " &
rK   r/   r   r3   rY   c                C  sP   t | dddu rLi }| j D ] \}}| }|tur|||< qt| d| dS )a  This function is meant to behave like a BaseModel method to initialise private attributes.

    It takes context as an argument since that's what pydantic-core passes when calling it.

    Args:
        self: The BaseModel instance.
        context: The context.
    Z__pydantic_private__N)r   r`   r   get_defaultr
   object_setattr)r>   rZ   Zpydantic_privater   private_attrdefaultrB   rB   rC   r[     s    	
r[   rM   rL   zCallable[..., Any] | None)rS   rR   r6   c                 C  s8   d| v r| d S ddl m} t|d}||jur4|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.r^   r   r.   N)r   r/   r   r^   )rS   rR   r/   r^   rB   rB   rC   r~   *  s    

r~   zset[str]zdict[str, ModelPrivateAttr])rS   r}   base_class_varsbase_class_fieldsr6   c              	     s  ddl m}m m} |t  }i }| di }d|v s>d| v rFtdt }	t| 	 D ]\}
}|
dksX|
dkrvqXqXt
|tr|j| d krd	| v r|j| d	 rqXqXt
||s|jjd
kr|	|
 qXqXt
| r*|
drtd|
dn$t|
rtdd|
 d|
d|||
< | |
= qXt
||rht|
sh|
dpNd}td|d|
dqX|
drxqXqXt|
r|
|vst||
 s(||d||
< | |
= qX|
|v rqXqX|
|vrX|
|v rtd|
dddqXt
||rtd|
dddqXtd|
 d|d|
 dddqX|	 D ]\}}t|r2||vr2||	vr2t|s2||vr2t|ddd
kr2t|rt|^}}t fdd |D d}|dur|||< q2| ||< q2|S )!a  Iterate over the namespace and:
    * gather private attributes
    * check for items which look like fields but are not (e.g. have no annotation) and warn.

    Args:
        namespace: The attribute dictionary of the class to be created.
        ignored_types: A tuple of ignore types.
        base_class_vars: A set of base class class variables.
        base_class_fields: A set of base class fields.

    Returns:
        A dict contains private attributes info.

    Raises:
        TypeError: If there is a `__root__` field in model.
        NameError: If private attribute name is invalid.
        PydanticUserError:
            - If a field does not have a type annotation.
            - If a field on base class was overridden by a non-annotated attribute.
    r   )r+   r,   r-   __annotations__Z__root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rX   Z__pydantic_extra__rE   rF   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of rp   zJPrivate attributes must not use valid field names; use sunder names, e.g. _z instead of Zmy_fieldz>Fields must not use names with leading underscores; e.g., use )r   zField z defined on a base class was overridden by a non-annotated attribute. All field definitions, including overrides, require a type annotation.zmodel-field-overridden)codez requires a type annotationzmodel-field-missing-annotationz)A non-annotated attribute was detected: `z = z3`. All model fields require a type annotation; if `z` is not meant to be a field, you may be able to resolve this error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.Nc                 3  s   | ]}t | r|V  qd S re   )r9   )rg   r5   r,   rB   rC   ri     rj   z$inspect_namespace.<locals>.<genexpr>)fieldsr+   r,   r-   default_ignored_typesr8   r   r   r   r   r9   rP   rE   rF   
startswithrA   add	NameErrorr   lstripr   r%   r   r   r$   typing_extensionsget_argsnext)rS   r}   r   r   r+   r-   Zall_ignored_typesr   Zraw_annotationsignored_namesvar_namevalueZsuggested_nameZann_nameZann_typer   metadatar   rB   r   rC   r|   6  s    









r|   type[BaseModel])r   rR   r6   c                 C  s<   t |d}t| }|d tjhv s2t|dd |jkr8|| _d S )Nru   __code__)r   make_hash_funcr2   ru   r   r   )r   rR   Zbase_hash_funcZnew_hash_funcrB   rB   rC   r     s    
 r   )r   r6   c                   s6   | j rtj| j   ndd  ddd fdd}|S )Nc                 S  s   dS )Nr   rB   )r   rB   rB   rC   <lambda>  rj   z make_hash_func.<locals>.<lambda>r   int)r>   r6   c                   s:   zt  | jW S  ty4   t  t| j Y S 0 d S re   )hashr   KeyErrorr(   r   getterrB   rC   	hash_func  s    z!make_hash_func.<locals>.hash_func)r   operator
itemgetterr   )r   r   rB   r   rC   r     s    
r   r   )r   rR   r   rw   r6   c           	      C  sl   t | }t| ||||d\}}|| _| j| |D ]2}| j|d}|dur4|jtur4t	| ||j q4dS )a.  Collect and set `cls.model_fields` and `cls.__class_vars__`.

    Args:
        cls: BaseModel or dataclass.
        bases: Parents of the class, generally `cls.__bases__`.
        config_wrapper: The config wrapper instance.
        types_namespace: Optional extra namespace to look for types in.
    )typevars_mapN)
r   r   r   r_   r   r`   popr   r
   setattr)	r   rR   r   rw   r   r   r   r4   r   rB   rB   rC   r     s    r   )rv   rx   r1   rN   zdict[str, Any] | NonerO   )r   rQ   r   rv   rw   rx   r6   c             
   C  s8  t | }t|||}tt|jdd|dd}|jrJd|jv rJt| | dS z| | |}	W nB t	y }
 z*|rp t| |d|
j
 d W Y d}
~
dS d}
~
0 0 || }z||	}	W n  |jy   t| | Y dS 0 |	| _t|	| |p| j| j| rdnd	||j| _t|	|| _d
| _tdt| j| j|d| _d
S )a  Finish building a model class.

    This logic must be called after class has been created since validation functions must be bound
    and `get_type_hints` requires a class object.

    Args:
        cls: BaseModel or dataclass.
        cls_name: The model or dataclass name.
        config_wrapper: The config wrapper instance.
        raise_errors: Whether to raise errors.
        types_namespace: Optional extra namespace to look for types in.
        create_model_module: The module of the class to be created, if created by `create_model`.

    Returns:
        `True` if the model is successfully completed, else `False`.

    Raises:
        PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
            and `raise_errors=True`.
    F)Zfrom_dunder_get_core_schemaunpack)Zref_modemodelr7   NZcreate_modelr/   T__signature__)initr   r   )r   r   r!   r   Zgenerate_schemaZdefer_buildZexperimental_defer_build_moder    Z__get_pydantic_core_schema__r   r   core_configZclean_schemaZCollectedInvalidZ__pydantic_core_schema__r   rE   rF   Zplugin_settingsr   r   Z__pydantic_serializer__r   r'   r"   r   r   r   )r   rQ   r   rv   rw   rx   r   Z
gen_schemahandlerZschemaer   rB   rB   rC   r     sX    


	r   c                 C  s   | j  D ]6\}}|j }dur
t|}|| | t| || q
| j D ]J\}}|j }durLtt|j	dsLt||j	}|| | t| || qLdS )z8Set data descriptors on the class for deprecated fields.N__deprecated__)
r   r   Zdeprecation_message_DeprecatedFieldDescriptorr   r   r   r   r   wrapped_property)r   fieldZ
field_infomsgdescZcomputed_field_inforB   rB   rC   r   <  s    r   c                   @  sf   e Zd ZU dZded< ddddddd	Zd
dddddZdddddddZddddddZdS )r   aM  Data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.

    Attributes:
        msg: The deprecation message to be emitted.
        wrapped_property: The property instance if the deprecated field is a computed field, or `None`.
        field_name: The name of the field being deprecated.
    r1   
field_nameNzproperty | Noner3   )r   r   r6   c                 C  s   || _ || _d S re   )r   r   )r>   r   r   rB   rB   rC   r   Z  s    z#_DeprecatedFieldDescriptor.__init__r   )r   r   r6   c                 C  s
   || _ d S re   )r   )r>   r   r   rB   rB   rC   r   ^  s    z'_DeprecatedFieldDescriptor.__set_name__zBaseModel | Noneztype[BaseModel] | Noner   )r   obj_typer6   c                 C  sJ   |d u rt | jtj| jtjdd | jd ur>| j||S |j	| j S )Nr   ra   )
r   r   r:   r;   r   builtinsDeprecationWarningr   __get__r   )r>   r   r   rB   rB   rC   r   a  s    

z"_DeprecatedFieldDescriptor.__get__r	   )r   r   r6   c                 C  s   t | jd S re   )r   r   )r>   r   r   rB   rB   rC   __set__n  s    z"_DeprecatedFieldDescriptor.__set__)N)N)	rD   rE   rF   rG   r   r   r   r   r   rB   rB   rB   rC   r   O  s   
r   c                   @  s:   e Zd ZdZddddZddddZd	dd
dZdS )_PydanticWeakRefa  Wrapper for `weakref.ref` that enables `pickle` serialization.

    Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related
    to abstract base classes (`abc.ABC`). This class works around the issue by wrapping
    `weakref.ref` instead of subclassing it.

    See https://github.com/pydantic/pydantic/issues/6763 for context.

    Semantics:
        - If not pickled, behaves the same as a `weakref.ref`.
        - If pickled along with the referenced object, the same `weakref.ref` behavior
          will be maintained between them after unpickling.
        - If pickled without the referenced object, after unpickling the underlying
          reference will be cleared (`__call__` will always return `None`).
    r   )r   c                 C  s    |d u rd | _ nt|| _ d S re   )_wrweakrefref)r>   r   rB   rB   rC   r     s    z_PydanticWeakRef.__init__r   c                 C  s   | j d u rd S |   S d S re   )r   r   rB   rB   rC   __call__  s    
z_PydanticWeakRef.__call__z4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS re   )r   r   rB   rB   rC   
__reduce__  s    z_PydanticWeakRef.__reduce__N)rD   rE   rF   rG   r   r   r   rB   rB   rB   rC   r   r  s   r   )dr6   c              	   C  sR   | du rdS i }|   D ]4\}}zt|}W n tyB   |}Y n0 |||< q|S )aX  Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs.

    We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values
    in a WeakValueDictionary.

    The `unpack_lenient_weakvaluedict` function can be used to reverse this operation.
    N)r   r   r   )r   resultr4   r5   proxyrB   rB   rC   r     s    

r   c                 C  sP   | du rdS i }|   D ]2\}}t|trB| }|durJ|||< q|||< q|S )zAInverts the transform performed by `build_lenient_weakvaluedict`.N)r   r9   r   )r   r   r4   r5   rB   rB   rC   r     s    


r   r   c                  C  s   ddl m}  ttttt| tfS )Nr   ComputedFieldInfo)r   r  r   r   r   r   r   r)   r  rB   rB   rC   r     s    r   )^rG   
__future__r   Z_annotationsr   r   r   r:   r   abcr   r   r   typesr   r   r   r   r	   r   Zpydantic_corer
   r   r   r   errorsr   r   Zplugin._schema_validatorr   r   r   _configr   Z_decoratorsr   r   r   r   _fieldsr   r   r   Z_generate_schemar   Z	_genericsr   r   Z_mock_val_serr    Z_schema_generation_sharedr!   
_signaturer"   Z_typing_extrar#   r$   r%   r&   Z_utilsr'   r(   Z_validate_callr)   r   r   r*   ZPydanticModelFieldr+   r,   r-   ZPydanticModelPrivateAttrr   r/   r   r2   __setattr__r   r   r0   rK   r[   r~   r|   r   r   r   r   r   r   r   r   r   r   rB   rB   rB   rC   <module>   sn    Zv#U##