o
    3h                     @  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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 ddlmZm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& ddl'm(Z( ddlm)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZGmHZHmIZImJZJ ddlKmLZLmMZM erddlNmOZP ddlNmQZQmRZR ddlNmSZT ddlUmVZV neW ZPeW ZTeWjXZYG dd  d eZZ[d!d"dfd'd(Z\ed)Z]ed*ePeTe\fd+G d,d- d-e
Z^dgd2d3Z_dhd9d:Z`didAdBZadjdEdFZbdkdGdHZcdldMdNZdd*d*ddOdmdVdWZedndXdYZfG dZd[ d[ZgG d\d] d]Zhdod`daZidodbdcZjedpdddeZkdS )qz"Private logic for creating models.    )annotationsN)ABCMeta)cachepartialwraps)FunctionType)TYPE_CHECKINGAnyCallableGenericLiteralNoReturnTypeVarcast)PydanticUndefinedSchemaSerializer)TypeAliasTypedataclass_transform
deprecatedget_args
get_origin)typing_objects   )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rebuild_model_fields)GenerateSchemaInvalidSchemaError)PydanticGenericMetadataget_model_typevars_map)import_cached_base_modelimport_cached_field_info)set_model_mocks)
NsResolver)generate_pydantic_signature)_make_forward_refeval_type_backportis_classvar_annotationparent_frame_namespace)LazyClassAttributeSafeGetItemProxy)Field)	FieldInfoModelPrivateAttr)PrivateAttr)	BaseModelc                      s"   e Zd ZdZd
 fdd	Z  ZS )_ModelNamespaceDictz{A dictionary subclass that intercepts attribute setting on model classes and
    warns about overriding of decorators.
    kstrvobjectreturnNonec                   sP   |  |d }|r!||ur!t|tr!tjd| d|jj ddd t ||S )N`z"` overrides an existing Pydantic `z` decoratorr   
stacklevel)	get
isinstancer!   warningswarndecorator_infodecorator_reprsuper__setitem__)selfr=   r?   existing	__class__ a/var/www/html/chatgem/venv/lib/python3.10/site-packages/pydantic/_internal/_model_construction.pyrM   8   s   z_ModelNamespaceDict.__setitem__)r=   r>   r?   r@   rA   rB   )__name__
__module____qualname____doc__rM   __classcell__rR   rR   rP   rS   r<   3   s    r<   FinitrZ   Literal[False]rA   r	   c                 C     dS )zOnly for typing purposes. Used as default value of `__pydantic_fields_set__`,
    `__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when
    synthesizing the `__init__` signature.
    NrR   rY   rR   rR   rS   NoInitFieldC       r]   _TT)kw_only_defaultfield_specifiersc                      s   e Zd Z			d-d. fddZesd/ddZed0ddZd1 fddZe	j
Z
e	jZed2d!d"Zeed#dd$d3d&d'Zed4d(d)Zd5 fd+d,Z  ZS )6ModelMetaclassNTcls_namer>   basestuple[type[Any], ...]	namespacedict[str, Any]__pydantic_generic_metadata__PydanticGenericMetadata | None#__pydantic_reset_parent_namespace__bool_create_model_module
str | Nonekwargsr	   rA   typec           "        s
  |rt jdkr,d|v r|d }n!ddlm}	m}
m} || }r)|
||	jd}n	i }n|di }| |\}}}t	
||||}|j|d< t|||j||}|sT|rqt||  durmt d: fdd}||d< nt|d< ||d< i |||d< tdt j| |||fi |}t }|j}t|v r|t||k rtjtddd t|jdd |_|j|ju rdnd|_i |_ t!"||_#|j#$| |r||_%nt|di ddt|ddprlrlt&fddD slddl'm(} t)fd dD }|v r0|vr0d!*d"d# |D }|j+ d$| d%|j+ d&| d'}t,|| }d!*d(d# |D }d)| d*}d+| d,}t|vrhd!*d-d# |D |g }|d.|j+ d/| d07 }t,|ddd1|_%d|_-|. D ]\}}|/|| qz|rt0t1 |_2t|d2d}t3|t4rt5|}t6|d3} t7||| d4 d5d6 |j#j8. D |_9|j:rt;| n	t<||| d|d7 |j=rd8|vrt>|| t||j?di | |S d9D ]	}!|@|!d q|di A  t j| |||fi |S );a  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.
        )      __annotations__r   )Formatcall_annotate_function!get_annotate_from_class_namespace)formatmodel_configNrN   r;   contextr	   rA   rB   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)rN   rx   )original_model_post_initrR   rS   wrapped_model_post_init   s   
z7ModelMetaclass.__new__.<locals>.wrapped_model_post_initmodel_post_init__class_vars____private_attributes__type[BaseModel]zClasses should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) for pydantic generics to work properly.r   rD   __pydantic_base_init__Frh   
parametersrR   __parameters__c                 3  s    | ]}| v V  qd S NrR   .0x)r   rR   rS   	<genexpr>   s    z)ModelMetaclass.__new__.<locals>.<genexpr>)RootModelRootTypec                 3  s    | ]	}| vr|V  qd S r   rR   r   )parent_parametersrR   rS   r      s    z, c                 S     g | ]}|j qS rR   rT   r   rR   rR   rS   
<listcomp>       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 rR   )r>   r   rR   rR   rS   r      s    ztyping.Generic[]zJAll parameters must be present on typing.Generic; you should inherit from .c                 S  r   rR   r   r   rR   rR   rS   r      r   z- Note: `typing.Generic` must go last: `class (z): ...`))originargsr   __pydantic_parent_namespace__)parent_namespace)config_wrapperns_resolverc                 S     i | ]\}}||j qS rR   infor   r=   r?   rR   rR   rS   
<dictcomp>   s    z*ModelMetaclass.__new__.<locals>.<dictcomp>)raise_errorscreate_model_module__hash__)__pydantic_fields_set____pydantic_extra____pydantic_private__rN   r;   rx   r	   rA   rB   )Bsysversion_infoannotationlibrs   rt   ru   
FORWARDREFrF   _collect_bases_datar   	for_modelconfig_dictinspect_namespaceignored_typesget_model_post_initr   ry   r   rL   __new__r,   __mro__r   indexrH   rI   r   getattr__init____pydantic_custom_init__r|   __pydantic_post_init____pydantic_setattr_handlers__r    build__pydantic_decorators__update_from_configrh   all
root_modelr   tuplejoinrT   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr4   r   rG   dictunpack_lenient_weakvaluedictr/   set_model_fieldscomputed_fields__pydantic_computed_fields__defer_buildr.   complete_model_classfrozenset_default_hash_func__pydantic_init_subclass__popclear)"mcsrc   rd   rf   rh   rj   rl   rn   raw_annotationsrs   rt   ru   annotatebase_field_names
class_varsbase_private_attributesr   private_attributesr{   cls
BaseModel_mror   missing_parametersparameters_strerror_messagecombined_parametersgeneric_type_label	bases_strnameobjr   r   instance_slotrP   )rz   r   r   rS   r   S   s   




 $




zModelMetaclass.__new__itemc                 C  s(   | j d}|r||v r|| S t|)zNThis is necessary to keep attribute access working for class attribute access.r~   )__dict__rF   AttributeError)rN   r   r   rR   rR   rS   __getattr__  s   zModelMetaclass.__getattr__r   dict[str, object]c                 O  s   t  S r   )r<   )r   r   rn   rR   rR   rS   __prepare__#  s   zModelMetaclass.__prepare__subclasstype[_T]c                   s$   t jd| j ddd t |S )Nz>For performance reasons, virtual subclasses registered using 'zK.register()' are not supported in 'isinstance()' and 'issubclass()' checks.r   rD   )rH   rI   rV   rL   register)rN   r   rP   rR   rS   r   +  s
   zModelMetaclass.register6tuple[set[str], set[str], dict[str, ModelPrivateAttr]]c                 C  sj   t  }t }t }i }| D ]"}t||r/||ur/|t|di   ||j ||j q|||fS )N__pydantic_fields__)r,   set
issubclassupdater   keysr}   r~   )rd   r;   field_namesr   r   baserR   rR   rS   r   6  s   
z"ModelMetaclass._collect_bases_dataXThe `__fields__` attribute is deprecated, use the `model_fields` class property instead.)categorydict[str, FieldInfo]c                 C  s   t jdtdd t| di S )Nr   r   rD   r   )rH   rI   r   r   rN   rR   rR   rS   
__fields__E  s   zModelMetaclass.__fields__c                 C  s0   d| j vrdS td| j}tdd | D S )zWhether the fields where successfully collected (i.e. type hints were successfully resolves).

        This is a private attribute, not meant to be used outside Pydantic.
        r   Fr   c                 s  s    | ]}|j V  qd S r   )	_complete)r   
field_inforR   rR   rS   r   \  s    z>ModelMetaclass.__pydantic_fields_complete__.<locals>.<genexpr>)r   r   r   r   values)rN   field_infosrR   rR   rS   __pydantic_fields_complete__Q  s   
z+ModelMetaclass.__pydantic_fields_complete__	list[str]c                   s$   t t  }d|v r|d |S )Nr   )listrL   __dir__remove)rN   
attributesrP   rR   rS   r   ^  s   
zModelMetaclass.__dir__)NTN)rc   r>   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   r	   rA   ro   )r   r>   rA   r	   )r   r	   rn   r	   rA   r   )r   r   rA   r   )rd   re   rA   r   )rA   r   )rA   rk   )rA   r   )rT   rU   rV   r   r   r   classmethodr   r   ro   __instancecheck____subclasscheck__staticmethodr   propertyr   r   r   r   rX   rR   rR   rP   rS   rb   Q   s.     G
rb   rN   r;   rx   rB   c                C  sT   t | dddu r(i }| j D ]\}}| }|tur|||< qt| d| dS 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.
    r   N)r   r~   r   get_defaultr   object_setattr)rN   rx   pydantic_privater   private_attrdefaultrR   rR   rS   ry   e  s   	ry   rf   rg   rd   re   Callable[..., Any] | Nonec                 C  s2   d| v r| d S t  }t|d}||jur|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.r|   N)r,   r"   r|   )rf   rd   r;   r|   rR   rR   rS   r   w  s   

r   r   r   base_class_varsset[str]base_class_fieldsdict[str, ModelPrivateAttr]c              
     s
  ddl m m} t }|t  }i }d|v sd| v rtdt }	t|  D ]\}
}|
dks3|
dkr4q't	|t
rP|j| d krPd| v rP|j| d  d	rPq't	||s[|jjd
kra|	|
 q't	| r|
drstd|
d	t|
rtdd|
 d|
d	|||
< | |
= q't	||rt|
s|
dpd}td|d|
d	|
drq't|
r|
|vst||
 st ||d||
< | |
= q'|
|v rq'|
|vr|
|v rtd|
dddt	||rtd|
dddtd|
 d|d|
 dddq'| D ]~\}}t|r||vr||	vrt|s||vrt|ddd
krt	|trWtd}|durWztt|ddd |j|jd!}W n ttfyV   Y nw t t!|r|t"|^}}t# fd"d#|D d}|dur||||< q| ||< q|S )$aJ  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.
        raw_annotations: The (non-evaluated) annotations of the model.
        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   )r9   r:   __root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rw   r   rU   rV   r   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of zJPrivate attributes must not use valid field names; use sunder names, e.g. _z instead of 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']`.NFT)is_argumentis_class)globalnslocalnsc                 3  s    | ]
}t | r|V  qd S r   )rG   )r   r?   r9   rR   rS   r     s    z$inspect_namespace.<locals>.<genexpr>)$fieldsr9   r:   r-   default_ignored_typesr   r   r   r   rG   ro   rU   rV   
startswithrQ   add	NameErrorr%   lstripr&   r3   r   r   r   r>   r   	_getframer2   r1   	f_globalsf_localsr   is_annotatedr   r   next)rf   r   r   r  r  r:   r8   all_ignored_typesr   ignored_namesvar_namevaluesuggested_nameann_nameann_typeframer  metadatar  rR   r  rS   r     s   














r   r   r   c                 C  s@   t |d}t| }|d tjhv st|dd |jkr|| _d S d S )Nr   __code__)r"   make_hash_funcr@   r   r   r.  )r   rd   base_hash_funcnew_hash_funcrR   rR   rS   r     s
   
 
r   c                   s0   | j rtj| j   ndd  d	 fdd}|S )
Nc                 S  r\   )Nr   rR   )r  rR   rR   rS   <lambda>  r^   z make_hash_func.<locals>.<lambda>rN   r	   rA   intc                   s6   zt  | jW S  ty   t  t| j Y S w r   )hashr   KeyErrorr6   r   getterrR   rS   	hash_func  s
   z!make_hash_func.<locals>.hash_func)rN   r	   rA   r3  )r   operator
itemgetterr   )r   r8  rR   r6  rS   r/    s   
r/  r   r   r   NsResolver | Nonec                 C  sj   t | }t| |||d\}}|| _| j| |D ]}| j|d}|dur2|jtur2t	| ||j qdS )zCollect and set `cls.__pydantic_fields__` and `cls.__class_vars__`.

    Args:
        cls: BaseModel or dataclass.
        config_wrapper: The config wrapper instance.
        ns_resolver: Namespace resolver to use when getting model annotations.
    )typevars_mapN)
r+   r$   r   r}   r   r~   r   r	  r   setattr)r   r   r   r<  r  r   r=   r(  rR   rR   rS   r   )  s   r   )r   call_on_complete_hookr   r/   r   rk   r>  r   rm   c             
   C  s  t | }| jsEzt| |||d| _W n& ty8 } zt|}t| d|j d |r.||W Y d}~nd}~ww |s@| js@dS | jsEJ t	|||}	z|	
| }
W n  tyr } z|r] t| d|j d W Y d}~dS d}~ww |j| jd}z|	|
}
W n ty   t|  Y dS w dd | jj D | _t|  |
| _t|
| |p| j| j|rdnd	||j| _t|
|| _td
tt| j| j|j |j!d| _"d| _#|r| $  dS )aK  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.
        config_wrapper: The config wrapper instance.
        ns_resolver: The namespace resolver instance to use during schema building.
        raise_errors: Whether to raise errors.
        call_on_complete_hook: Whether to call the `__pydantic_on_complete__` hook.
        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`.
    )r   r   r<  rC   NF)titlec                 S  r   rR   r   r   rR   rR   rS   r     s    z(complete_model_class.<locals>.<dictcomp>create_modelr;   __signature__)rZ   r  validate_by_nameextraT)%r+   r   r'   r   r  r   from_name_errorr.   r   r(   generate_schemacore_configrT   clean_schemar)   r   r   r   r   set_deprecated_descriptors__pydantic_core_schema__r   rU   rV   plugin_settings__pydantic_validator__r   __pydantic_serializer__r5   r   r0   r   rB  rC  rA  r   __pydantic_on_complete__)r   r   r   r   r>  r   r<  eexc
gen_schemaschemarF  rR   rR   rS   r   H  s   



	r   c                 C  s   | j  D ]\}}|j }dur t|}|| | t| || q| j D ]%\}}|j }durKtt|j	dsKt||j	}|| | t| || q&dS )z8Set data descriptors on the class for deprecated fields.N__deprecated__)
r   r   deprecation_message_DeprecatedFieldDescriptorr   r=  r   hasattrr#   wrapped_property)r   fieldr   msgdesccomputed_field_inforR   rR   rS   rH    s   rH  c                   @  sF   e Zd ZU dZded< ddd
dZdddZddddZd ddZdS )!rT  aW  Read-only 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.
    r>   
field_nameNrX  rV  property | NonerA   rB   c                 C  s   || _ || _d S r   )rX  rV  )rN   rX  rV  rR   rR   rS   r     s   
z#_DeprecatedFieldDescriptor.__init__r   r   r   c                 C  s
   || _ d S r   )r[  )rN   r   r   rR   rR   rS   r        
z'_DeprecatedFieldDescriptor.__set_name__r   BaseModel | Noneobj_typetype[BaseModel] | Noner	   c                 C  s`   |d u r| j d ur| j d |S t| jtj| jtdd | j d ur*| j ||S |j| j S )Nr   rD   )	rV  __get__r   r[  rH   rI   rX  DeprecationWarningr   )rN   r   r_  rR   rR   rS   ra    s   


z"_DeprecatedFieldDescriptor.__get__r(  r   c                 C  s
   t | jr   )r   r[  )rN   r   r(  rR   rR   rS   __set__  r]  z"_DeprecatedFieldDescriptor.__set__r   )rX  r>   rV  r\  rA   rB   )r   r   r   r>   rA   rB   )r   r^  r_  r`  rA   r	   )r   r	   r(  r	   rA   r   )	rT   rU   rV   rW   rr   r   r   ra  rc  rR   rR   rR   rS   rT    s   
 
rT  c                   @  s.   e Zd ZdZdddZdddZ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 | _ d S t|| _ d S r   )_wrweakrefref)rN   r   rR   rR   rS   r   	  s   
z_PydanticWeakRef.__init__rA   c                 C  s   | j d u rd S |   S r   )re  r   rR   rR   rS   __call__  s   
z_PydanticWeakRef.__call__4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS r   )rd  r   rR   rR   rS   
__reduce__  s   z_PydanticWeakRef.__reduce__N)r   r	   )rA   r	   )rA   ri  )rT   rU   rV   rW   r   rh  rj  rR   rR   rR   rS   rd    s
    

rd  ddict[str, Any] | Nonec              	   C  sR   | du rdS i }|   D ]\}}zt|}W n ty!   |}Y nw |||< 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   rd  r   )rk  resultr=   r?   proxyrR   rR   rS   r     s   
r   c                 C  sP   | du rdS i }|   D ]\}}t|tr!| }|dur |||< q|||< q|S )zAInverts the transform performed by `build_lenient_weakvaluedict`.N)r   rG   rd  )rk  rm  r=   r?   rR   rR   rS   r   /  s   

r   c                  C  s<   ddl m}  ttttt| tg}tj	dkr|
tj t|S )Nr   )ComputedFieldInfo)rp      )r  ro  r   r  r   r  r!   r   r   r   appendtypingr   )ro  r   rR   rR   rS   r  ?  s   

r  )rZ   r[   rA   r	   r   )rf   rg   rd   re   rA   r
  )rf   rg   r   rg   r   re   r  r  r  r  rA   r  )r   r   rd   re   rA   rB   )r   r   rA   r	   )r   r   r   r   r   r;  rA   rB   )r   r   r   r   r   r/   r   rk   r>  rk   r   rm   rA   rk   )r   r   rA   rB   )rk  rl  rA   rl  )rA   re   )lrW   
__future__r   _annotationsr9  r   rr  rH   rf  abcr   r  r   r   r   typesr   r   r	   r
   r   r   r   r   r   pydantic_corer   r   typing_extensionsr   r   r   r   r   typing_inspectionr   errorsr   r   plugin._schema_validatorr   r   r   _configr   _decoratorsr    r!   r"   r#   _fieldsr$   r%   r&   r'   _generate_schemar(   r)   	_genericsr*   r+   _import_utilsr,   r-   _mock_val_serr.   _namespace_utilsr/   
_signaturer0   _typing_extrar1   r2   r3   r4   _utilsr5   r6   r  r7   PydanticModelFieldr8   r9   r:   PydanticModelPrivateAttrmainr;   r@   __setattr__r  r   r<   r]   r_   rb   ry   r   r   r   r/  r   r   rH  rT  rd  r   r   r  rR   rR   rR   rS   <module>   s|    (  


 



$
x%
#
