U
    ={f2                    @  s  U 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	m
Z
 ddlmZmZmZmZmZmZmZmZmZ ddlZddlZddl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" dd
l#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l0m1Z1m2Z2m3Z3m4Z4m5Z5 ddlm6Z6 edddZ7eee8ef ddf Z9eee: ee8 ee:ef ee8ef df Z;de<d< ej=rddl>m?Z? ddl@mAZA ddlmBZBmCZCmDZD ddlmEZE ddlFmGZGmHZH ddlImJZK ddlLmMZMmNZNmOZO ddlLmPZQ ne6ZRdZSejTZUG dd dejVd ZWejXdddeYddd!d"d#d$d%d"d&d'd(d)d*	d+d,ZZejXddeYddd-d"d#d$d.d"d&d'd(d/d*	d0d,ZZdddddddd1d"d#d$d2d$d&d'd3d(d/d4
d5d,ZZe$eYZ[dS )6zLogic for creating models.    )annotationsN)copydeepcopy)	AnyClassVarDict	GeneratorLiteralSetTupleTypeVarUnionPydanticUndefined)	TypeAlias   )
_config_decorators_fields_forward_ref	_generics_mock_val_ser_model_construction_repr_typing_extra_utils)getattr_migration)AliasChoices	AliasPath)GetCoreSchemaHandlerGetJsonSchemaHandler)
ConfigDict)PydanticUndefinedAnnotationPydanticUserError)DEFAULT_REF_TEMPLATEGenerateJsonSchemaJsonSchemaModeJsonSchemaValuemodel_json_schema)PydanticDeprecatedSince20Model	BaseModel)boundr   IncEx)	Signature)Path)
CoreSchemaSchemaSerializerSchemaValidator)Unpack)AbstractSetIntStrMappingIntStrAny)Protocol)ComputedFieldInfo	FieldInfoModelPrivateAttr)Field)r+   create_modelc                      s8  e Zd ZU dZejrded< ded< ded< ded	< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ed d!Zd"ed#< ed d!Z	d$ed%< ed d!Z
d"ed&< n4i Zi Ze Zd'Zejd(d)d*d+Zejd(d,d*d+Zd-Ze Zd Zd Zd.d/d0d1d2Zd3e_ed"d4d5d6Zed$d4d7d8Zedd9d:d.d;d<d=d>Z d'd d?d;d"d@d;dAdBdCZ!dDd'd'd'd d d d d d3d dEdFdGdGd"d@d@d@d@d@dHd@dIdJdKdLZ"d'd'd'd'd d d d d d3d dMdNdGdGd"d@d@d@d@d@dHd@dOdPdQdRZ#ed3e$e%dSfd@dOdTdUdIdVdWdXZ&edYdOdZd[d\Z'd.d/d]d^d_Z(ed d3d`d'dad@d@dbd"dcdddedfZ)ed'd'd'dgd9d.dcdcd"d;dhdidjZ*ed'd'dkd9dldcd"d;dmdndoZ+ed'd'dkd9d.dcd"d;dpdqdrZ,edsdtdudvdwdxZ-edudydzd{d|d}Z.ed.d/d~ddZ/dddddZ0d;d;dddZ1d d;dd;dddZ2ejsdOd.d fddZ3dOd.d/dddZ4dOd.dddZ5dOd.d/dddZ6dd4ddZ7dd/dddZ8ejsd.d@dddZ9ejrddddZ:dd4ddZ;dOd4ddZ<dd4ddZ=e>j?j@Z@e>j?jAZAe>j?jBZBe>j?jCZCdOd4ddZDeeEjFdd'ddd4ddZGeeEjFdd'dd$d4ddZHeEjFdd'dd'd'd d d d ddGdGd@d@d@d@ddddZIeEjFdd'dd'd'd d d d eJeJddGdGd@d@d@d@dd@d.dOd
ddZKeeEjFdd'dd9d.d;dÜddńZLeeEjFdd'dd'dd'd dȜd9dddOdd@d;d̜dd΄ZMeeEjFdd'dd'dd'd dȜd9dddOdd@d;dќddӄZNeeEjFdd'dd9d.d;dÜddքZOeeEjFdd'ddd9d:d.d;d<ddلZPeEjFdd'dd'd'd'd dۜd;dddd@d;dޜddZQeeEjFdd'dd3e$fd@dOddddZReeEjFdd'dd3e$dd@dOd.dOdddZSeeEjFdd'dd9d.d;dddZTeeEjFdd'dd.d/dddZUeEjFdd'dd.d.d.dddZVeEjFdd'dd.d.d.dddZWeeEjFdd'dd.d.d.dddZXeEjFdd'dd.d.d.dddZY  ZZS (  r+   a}  Usage docs: https://docs.pydantic.dev/2.7/concepts/models/

    A base class for creating Pydantic models.

    Attributes:
        __class_vars__: The names of classvars defined on the model.
        __private_attributes__: Metadata about the private attributes of the model.
        __signature__: The signature for instantiating the model.

        __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
        __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
        __pydantic_custom_init__: Whether the model has a custom `__init__` function.
        __pydantic_decorators__: Metadata containing the decorators defined on the model.
            This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
        __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
            __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
        __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
        __pydantic_post_init__: The name of the post-init method for the model, if defined.
        __pydantic_root_model__: Whether the model is a `RootModel`.
        __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the model.
        __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the model.

        __pydantic_extra__: An instance attribute with the values of extra fields from validation when
            `model_config['extra'] == 'allow'`.
        __pydantic_fields_set__: An instance attribute with the names of fields explicitly set.
        __pydantic_private__: Instance attribute with the values of private attributes set on the model instance.
    zClassVar[ConfigDict]model_configzClassVar[dict[str, FieldInfo]]model_fieldsz&ClassVar[dict[str, ComputedFieldInfo]]model_computed_fieldszClassVar[set[str]]__class_vars__z%ClassVar[dict[str, ModelPrivateAttr]]__private_attributes__zClassVar[Signature]__signature__zClassVar[bool]__pydantic_complete__zClassVar[CoreSchema]__pydantic_core_schema__Z__pydantic_custom_init__z$ClassVar[_decorators.DecoratorInfos]__pydantic_decorators__z+ClassVar[_generics.PydanticGenericMetadata]__pydantic_generic_metadata__zClassVar[dict[str, Any] | None]__pydantic_parent_namespace__z+ClassVar[None | Literal['model_post_init']]__pydantic_post_init____pydantic_root_model__zClassVar[SchemaSerializer]__pydantic_serializer__zClassVar[SchemaValidator]__pydantic_validator__F)initdict[str, Any] | None__pydantic_extra__zset[str]__pydantic_fields_set____pydantic_private__NzXPydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly	validatorzbase-model-instantiated)Z
val_or_sercode
serializer)__dict__rN   rM   rO   r   None)datareturnc                K  s   d}| j j|| d dS )a/  Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        T)Zself_instanceNrJ   Zvalidate_python)selfrU   __tracebackhide__ rZ   L/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/pydantic/main.py__init__   s    	zBaseModel.__init__T)rV   c                 C  s   | j S )zGet extra fields set during validation.

        Returns:
            A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
        )rM   rX   rZ   rZ   r[   model_extra   s    zBaseModel.model_extrac                 C  s   | j S )zReturns the set of fields that have been explicitly set on this model instance.

        Returns:
            A set of strings representing the fields that have been set,
                i.e. that were not filled from defaults.
        )rN   r]   rZ   rZ   r[   model_fields_set   s    zBaseModel.model_fields_settype[Model]zset[str] | Noner*   )cls_fields_setvaluesrV   c                 K  s  |  | }i }t }| j D ]\}}|jdk	rV|j|krV||j||< || ||kr|jdk	rt|jt	r||jj
n|jg}|D ]f}	t|	tr|	|kr||	||< ||  qqt|	tr|	|}
|
tk	r|
||< ||  qq||kr||kr||||< || q| s|jdd||< q|dkrD|}| jddkrhdd | D nd}t|d| t|d	| | jst|d
| | jr|d t|dr|jdk	r| D ] \}}||jkr||j|< qn| jst|dd |S )a_  Creates a new instance of the `Model` class with validated data.

        Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
        Default values are respected, but no other validation is performed.

        !!! note
            `model_construct()` generally respects the `model_config.extra` setting on the provided model.
            That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
            and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
            Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
            an error if extra values are passed, but they will be ignored.

        Args:
            _fields_set: The set of field names accepted for the Model instance.
            values: Trusted or pre-validated data dictionary.

        Returns:
            A new instance of the `Model` class with validated data.
        NT)Zcall_default_factoryextraallowc                 S  s   i | ]\}}||qS rZ   rZ   .0kvrZ   rZ   r[   
<dictcomp>  s      z-BaseModel.model_construct.<locals>.<dictcomp>rS   rN   rM   rO   )__new__setr=   itemsaliaspopaddZvalidation_alias
isinstancer   choicesstrr   Zsearch_dict_for_pathr   Zis_requiredget_defaultr<   get_object_setattrrH   rG   model_post_inithasattrrO   r@   )ra   rb   rc   mZfields_values
fields_setnamefieldZvalidation_aliasesrn   value_extrarh   ri   rZ   rZ   r[   model_construct   s\    









&
zBaseModel.model_construct)updatedeepbool)rX   r   r   rV   c                C  s   |r|   n|  }|r| jddkrl| D ]8\}}|| jkrN||j|< q0|jdkr^i |_||j|< q0n|j| |j	|
  |S )a  Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#model_copy

        Returns a copy of the model.

        Args:
            update: Values to change/add in the new model. Note: the data is not validated
                before creating the new model. You should trust this data.
            deep: Set to `True` to make a deep copy of the model.

        Returns:
            New model instance.
        rd   re   N)__deepcopy____copy__r<   ru   rm   r=   rS   rM   r   rN   keys)rX   r   r   copiedrh   ri   rZ   rZ   r[   
model_copy  s    

zBaseModel.model_copypython)modeincludeexcludecontextby_aliasexclude_unsetexclude_defaultsexclude_none
round_tripwarningsserialize_as_anyz!Literal[('json', 'python')] | strr-   z)bool | Literal[('none', 'warn', 'error')]zdict[str, Any])r   r   r   r   r   r   r   r   r   r   r   rV   c                C  s$   | j j| |||||||||	|
|dS )a  Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#modelmodel_dump

        Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

        Args:
            mode: The mode in which `to_python` should run.
                If mode is 'json', the output will only contain JSON serializable types.
                If mode is 'python', the output may contain non-JSON-serializable Python objects.
            include: A set of fields to include in the output.
            exclude: A set of fields to exclude from the output.
            context: Additional context to pass to the serializer.
            by_alias: Whether to use the field's alias in the dictionary key if defined.
            exclude_unset: Whether to exclude fields that have not been explicitly set.
            exclude_defaults: Whether to exclude fields that are set to their default value.
            exclude_none: Whether to exclude fields that have a value of `None`.
            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

        Returns:
            A dictionary representation of the model.
        )r   r   r   r   r   r   r   r   r   r   r   )rI   Z	to_python)rX   r   r   r   r   r   r   r   r   r   r   r   rZ   rZ   r[   
model_dump5  s    &zBaseModel.model_dumpindentr   r   r   r   r   r   r   r   r   r   z
int | Noners   )r   r   r   r   r   r   r   r   r   r   r   rV   c                C  s(   | j j| |||||||||	|
|d S )a-  Usage docs: https://docs.pydantic.dev/2.7/concepts/serialization/#modelmodel_dump_json

        Generates a JSON representation of the model using Pydantic's `to_json` method.

        Args:
            indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
            include: Field(s) to include in the JSON output.
            exclude: Field(s) to exclude from the JSON output.
            context: Additional context to pass to the serializer.
            by_alias: Whether to serialize using field aliases.
            exclude_unset: Whether to exclude fields that have not been explicitly set.
            exclude_defaults: Whether to exclude fields that are set to their default value.
            exclude_none: Whether to exclude fields that have a value of `None`.
            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

        Returns:
            A JSON string representation of the model.
        r   )rI   to_jsondecode)rX   r   r   r   r   r   r   r   r   r   r   r   rZ   rZ   r[   model_dump_jsonj  s    $zBaseModel.model_dump_jsonZ
validationztype[GenerateJsonSchema]r&   )r   ref_templateschema_generatorr   rV   c                 C  s   t | ||||dS )a  Generates a JSON schema for a model class.

        Args:
            by_alias: Whether to use attribute aliases or not.
            ref_template: The reference template.
            schema_generator: To override the logic used to generate the JSON schema, as a subclass of
                `GenerateJsonSchema` with your desired modifications
            mode: The mode in which to generate the schema.

        Returns:
            The JSON schema for the given model class.
        )r   r   r   r   )r(   )ra   r   r   r   r   rZ   rZ   r[   r(     s        zBaseModel.model_json_schemaztuple[type[Any], ...])paramsrV   c                 C  s>   t | tjstddd |D }d|}| j d| dS )a}  Compute the class name for parametrizations of generic classes.

        This method can be overridden to achieve a custom naming scheme for generic BaseModels.

        Args:
            params: Tuple of types of the class. Given a generic class
                `Model` with 2 type variables and a concrete model `Model[str, int]`,
                the value `(str, int)` would be passed to `params`.

        Returns:
            String representing the new class where `params` are passed to `cls` as type variables.

        Raises:
            TypeError: Raised when trying to generate concrete names for non-generic models.
        z;Concrete names should only be generated for generic models.c                 S  s$   g | ]}t |tr|nt|qS rZ   )rq   rs   r   Zdisplay_as_typerg   paramrZ   rZ   r[   
<listcomp>  s     z5BaseModel.model_parametrized_name.<locals>.<listcomp>, [])
issubclasstypingGeneric	TypeErrorjoin__name__)ra   r   Zparam_namesZparams_componentrZ   rZ   r[   model_parametrized_name  s
    
z!BaseModel.model_parametrized_name)_BaseModel__contextrV   c                 C  s   dS )zOverride this method to perform additional initialization after `__init__` and `model_construct`.
        This is useful if you want to do some validation that requires the entire model to be initialized.
        NrZ   )rX   r   rZ   rZ   r[   rw     s    zBaseModel.model_post_init   )forceraise_errors_parent_namespace_depth_types_namespaceintzbool | None)r   r   r   r   rV   c          	      C  s   |s| j rdS d| jkr"t| d |dk	r4| }nV|dkrrtj|dpJi }t| jpZi }||}t	|| _nt| j}t
| |}| jddi}tj| | jtj|dd||dS dS )	a1  Try to rebuild the pydantic-core schema for the model.

        This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
        the initial attempt to build the schema, and automatic rebuilding fails.

        Args:
            force: Whether to force the rebuilding of the model schema, defaults to `False`.
            raise_errors: Whether to raise errors, defaults to `True`.
            _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
            _types_namespace: The types namespace, defaults to `None`.

        Returns:
            Returns `None` if the schema is already "complete" and rebuilding was not required.
            If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
        NrC   r   )Zparent_depthZdefer_buildF)check)r   types_namespace)rB   rS   delattrr   r   Zparent_frame_namespacer   Zunpack_lenient_weakvaluedictrF   Zbuild_lenient_weakvaluedictZget_cls_types_namespacer<   Zcomplete_model_classr   r   ConfigWrapper)	ra   r   r   r   r   r   Zframe_parent_nsZcls_parent_nsconfigrZ   rZ   r[   model_rebuild  s0    



zBaseModel.model_rebuildstrictfrom_attributesr   )ra   objr   r   r   rV   c                C  s   d}| j j||||dS )a  Validate a pydantic model instance.

        Args:
            obj: The object to validate.
            strict: Whether to enforce types strictly.
            from_attributes: Whether to extract data from object attributes.
            context: Additional context to pass to the validator.

        Raises:
            ValidationError: If the object could not be validated.

        Returns:
            The validated model instance.
        Tr   rW   )ra   r   r   r   r   rY   rZ   rZ   r[   model_validate  s       zBaseModel.model_validater   r   zstr | bytes | bytearray)ra   	json_datar   r   rV   c                C  s   d}| j j|||dS )a  Usage docs: https://docs.pydantic.dev/2.7/concepts/json/#json-parsing

        Validate the given JSON data against the Pydantic model.

        Args:
            json_data: The JSON data to validate.
            strict: Whether to enforce types strictly.
            context: Extra variables to pass to the validator.

        Returns:
            The validated Pydantic model.

        Raises:
            ValueError: If `json_data` is not a JSON string.
        Tr   )rJ   Zvalidate_json)ra   r   r   r   rY   rZ   rZ   r[   model_validate_json+  s    zBaseModel.model_validate_json)ra   r   r   r   rV   c                C  s   d}| j j|||dS )aR  Validate the given object contains string data against the Pydantic model.

        Args:
            obj: The object contains string data to validate.
            strict: Whether to enforce types strictly.
            context: Extra variables to pass to the validator.

        Returns:
            The validated Pydantic model.
        Tr   )rJ   Zvalidate_strings)ra   r   r   r   rY   rZ   rZ   r[   model_validate_stringsF  s    z BaseModel.model_validate_stringstype[BaseModel]r   r0   )sourcehandlerrV   c                C  s"   d| j kr| jd s| jS ||S )a  Hook into generating the model's CoreSchema.

        Args:
            source: The class we are generating a schema for.
                This will generally be the same as the `cls` argument if this is a classmethod.
            handler: Call into Pydantic's internal JSON schema generation.
                A callable that calls into Pydantic's internal CoreSchema generation logic.

        Returns:
            A `pydantic-core` `CoreSchema`.
        rC   origin)rS   rE   rC   )ra   r   r   rZ   rZ   r[   __get_pydantic_core_schema__\  s    

z&BaseModel.__get_pydantic_core_schema__r    r'   )core_schemar   rV   c                C  s   ||S )a_  Hook into generating the model's JSON schema.

        Args:
            core_schema: A `pydantic-core` CoreSchema.
                You can ignore this argument and call the handler with a new CoreSchema,
                wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
                or just call the handler with the original schema.
            handler: Call into Pydantic's internal JSON schema generation.
                This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
                generation fails.
                Since this gets called by `BaseModel.model_json_schema` you can override the
                `schema_generator` argument to that function to change JSON schema generation globally
                for a type.

        Returns:
            A JSON schema, as a Python object.
        rZ   )ra   r   r   rZ   rZ   r[   __get_pydantic_json_schema__t  s    z&BaseModel.__get_pydantic_json_schema__)kwargsrV   c                 K  s   dS )a  This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
        only after the class is actually fully initialized. In particular, attributes like `model_fields` will
        be present when this is called.

        This is necessary because `__init_subclass__` will always be called by `type.__new__`,
        and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
        `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

        This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
        any kwargs passed to the class definition that aren't used internally by pydantic.

        Args:
            **kwargs: Any keyword arguments passed to the class definition that aren't used internally
                by pydantic.
        NrZ   ra   r   rZ   rZ   r[   __pydantic_init_subclass__  s    z$BaseModel.__pydantic_init_subclass__z!type[Any] | tuple[type[Any], ...]z3type[BaseModel] | _forward_ref.PydanticRecursiveRef)typevar_valuesrV   c           
   
     s  t | |}|d k	r|S | tkr(tdt| ds@t|  d| jd sdtj| jkrdt|  dt	|t
st|f}t | | tt| jd | t    r r| }t | || n| jd }|s|}nt
 fdd|D }| jd	 p| }||}t
d
d t   D }t ||}	|	d k	rH|	W  5 Q R  S t | |||}|d k	rr|W  5 Q R  S z|jdd W n tk
r   Y nX t ||||}t | |||| W 5 Q R X |S )NzAType parameters should be placed on typing.Generic, not BaseModel__parameters__zG cannot be parametrized because it does not inherit from typing.Generic
parametersz is not a generic classargsc                 3  s   | ]}t | V  qd S N)r   Zreplace_types)rg   argZtypevars_maprZ   r[   	<genexpr>  s     z.BaseModel.__class_getitem__.<locals>.<genexpr>r   c                 S  s   i | ]
}|d qS r   rZ   r   rZ   rZ   r[   rj     s      z/BaseModel.__class_getitem__.<locals>.<dictcomp>   )r   )r   Zget_cached_generic_type_earlyr+   r   rx   rE   r   r   	__bases__rq   tupleZcheck_parameters_countdictzipr   Zall_identicalr   rc   Zset_cached_generic_typer   Ziter_contained_typevarsZgeneric_recursion_self_typeZget_cached_generic_type_later   r"   Zcreate_generic_submodel)
ra   r   cachedZsubmodelZparent_argsr   r   Z
model_namer   Zmaybe_self_typerZ   r   r[   __class_getitem__  sP    





zBaseModel.__class_getitem__)rX   rV   c                 C  s   t | }||}t|dt| j t|dt| j t|dt| j t| dr\| jdkrjt|dd nt|ddd | j	 D  |S )z$Returns a shallow copy of the model.rS   rM   rN   rO   Nc                 S  s   i | ]\}}|t k	r||qS rZ   r   rf   rZ   rZ   r[   rj     s       z&BaseModel.__copy__.<locals>.<dictcomp>)
typerk   rv   r   rS   rM   rN   rx   rO   rm   )rX   ra   ry   rZ   rZ   r[   r     s    
zBaseModel.__copy__zdict[int, Any] | None)rX   memorV   c                 C  s   t | }||}t|dt| j|d t|dt| j|d t|dt| j t| drd| j	dkrrt|dd n$t|dtdd | j	
 D |d |S )	z!Returns a deep copy of the model.rS   )r   rM   rN   rO   Nc                 S  s   i | ]\}}|t k	r||qS rZ   r   rf   rZ   rZ   r[   rj     s       z*BaseModel.__deepcopy__.<locals>.<dictcomp>)r   rk   rv   r   rS   rM   r   rN   rx   rO   rm   )rX   r   ra   ry   rZ   rZ   r[   r     s    
zBaseModel.__deepcopy__)itemrV   c              
     s4  t | d}||kr|| }t|dr6|| t| S z| j| W S  tk
r~ } ztt| jd||W 5 d }~X Y nX nzt | d}W n tk
r   d }Y nX | rz
|| W S  tk
 r } ztt| jd||W 5 d }~X Y nX n2t| j	|rt
 |S tt| jd|d S )Nr@   __get__ object has no attribute rM   )object__getattribute__rx   r   r   rO   KeyErrorAttributeErrorr   	__class__super)rX   r   Zprivate_attributes	attributeexcpydantic_extrar   rZ   r[   __getattr__  s*    
.

.zBaseModel.__getattr__)r{   r}   rV   c              	   C  s  || j kr4t|d| jj d| jj d| dn\t|s| jd ksR|| jkr`t| || n,| j| }t	|dr|
| | n
|| j|< d S | || t| j|d }t|tr|
| | n| jdd r| j| || n| jddkr|| jkrtd	| jj d
| d	n| jddkr|| jkr| jrZ|| jkrZ|| j|< n<zt| | W n  tk
r   || j|< Y nX t| || n|| j|< | j| d S )Nz is a ClassVar of `zR` and cannot be set on an instance. If you want to set a value on the class, use `.z
 = value`.__set__validate_assignmentrd   re   "z" object has no field ")r?   r   r   r   r   is_valid_field_namerO   r@   rv   rx   r   _check_frozengetattrrq   propertyr<   ru   rJ   r   r=   
ValueErrorr^   rM   rS   rN   rp   )rX   r{   r}   r   attrrZ   rZ   r[   __setattr__-  s<    
"





zBaseModel.__setattr__c              
   C  s   || j krx| j | }t|dr,||  d S z| j|= W d S  tk
rv } ztt| jd||W 5 d }~X Y nX | |d  || j	krt
| | n\| jd k	r|| jkr| j|= n>zt
| | W n, tk
r   tt| jd|Y nX d S )N
__delete__r   )r@   rx   r   rO   r   r   r   r   r   r=   r   __delattr__rM   )rX   r   r   r   rZ   rZ   r[   r   X  s&    



,

zBaseModel.__delattr__c                 C  sX   | j dd rd}nt| j|ddr.d}nd S ||f|d}tj| jj|gd S )NfrozenZfrozen_instanceFZfrozen_fieldr   locinput)	r<   ru   r   r=   pydantic_coreValidationErrorfrom_exception_datar   r   )rX   r{   r}   typerrorrZ   rZ   r[   r   r  s    zBaseModel._check_frozenzdict[Any, Any]c                 C  s0   | j }|rdd | D }| j| j| j|dS )Nc                 S  s   i | ]\}}|t k	r||qS rZ   r   rf   rZ   rZ   r[   rj     s       z*BaseModel.__getstate__.<locals>.<dictcomp>)rS   rM   rN   rO   )rO   rm   rS   rM   rN   )rX   privaterZ   rZ   r[   __getstate__  s    zBaseModel.__getstate__)staterV   c                 C  sD   t | d|d  t | d|d  t | d|d  t | d|d  d S )NrN   rM   rO   rS   )rv   )rX   r  rZ   rZ   r[   __setstate__  s    zBaseModel.__setstate__)otherrV   c                 C  s  t |tr| jd p| j}|jd p*|j}||krXt| dd t|dd krX| j|jks\dS | j|jkrldS t| j	 }| j	 |kr|j	 |krdS |rt
j| ndd }z|| j||jkW S  tk
r   t| j}t|j}||||k Y S X ntS d S )Nr   rO   FTc                 S  s   t jS r   )r   Z	_SENTINEL_rZ   rZ   r[   <lambda>      z"BaseModel.__eq__.<locals>.<lambda>)rq   r+   rE   r   r   rM   rS   r   r=   r   operator
itemgetterr   r   ZSafeGetItemProxyNotImplemented)rX   r  	self_typeZ
other_typer=   getterZself_fields_proxyZother_fields_proxyrZ   rZ   r[   __eq__  s.    
	zBaseModel.__eq__zUnpack[ConfigDict])r   c                 K  s   dS )a  This signature is included purely to help type-checkers check arguments to class declaration, which
            provides a way to conveniently set model_config key/value pairs.

            ```py
            from pydantic import BaseModel

            class MyModel(BaseModel, extra='allow'):
                ...
            ```

            However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
            of the config arguments, and will only receive any keyword arguments passed during class initialization
            that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

            Args:
                **kwargs: Keyword arguments passed to the class definition, which set model_config

            Note:
                You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
                *after* the class is fully initialized.
            NrZ   r   rZ   rZ   r[   __init_subclass__  s    zBaseModel.__init_subclass__TupleGeneratorc                 c  s6   dd | j  D E dH  | j}|r2| E dH  dS )zSo `dict(model)` works.c                 S  s"   g | ]\}}| d s||fqS r  )
startswithrf   rZ   rZ   r[   r     s     
 z&BaseModel.__iter__.<locals>.<listcomp>N)rS   rm   rM   )rX   rd   rZ   rZ   r[   __iter__  s    zBaseModel.__iter__c                 C  s   |    d| d dS )N(r   ))__repr_name____repr_str__r]   rZ   rZ   r[   __repr__  s    zBaseModel.__repr__z_repr.ReprArgsc                 #  s    j  D ](\}} j|}|r
|jr
||fV  q
zt d}W n tk
r\   d }Y nX |d k	r~dd | D E d H   fdd j D E d H  d S )NrM   c                 s  s   | ]\}}||fV  qd S r   rZ   rf   rZ   rZ   r[   r      s     z*BaseModel.__repr_args__.<locals>.<genexpr>c                 3  s&   | ]\}}|j r|t |fV  qd S r   )reprr   rf   r]   rZ   r[   r     s      )	rS   rm   r=   ru   r  r   r   r   r>   )rX   rh   ri   r|   r   rZ   r]   r[   __repr_args__  s    

zBaseModel.__repr_args__c                 C  s
   |  dS )N )r  r]   rZ   rZ   r[   __str__	  s    zBaseModel.__str__EThe `__fields__` attribute is deprecated, use `model_fields` instead.categoryzdict[str, FieldInfo]c                 C  s   t jdtd | jS )Nr  r  )r   warnr)   r=   r]   rZ   rZ   r[   
__fields__  s
     zBaseModel.__fields__MThe `__fields_set__` attribute is deprecated, use `model_fields_set` instead.c                 C  s   t jdtd | jS )Nr   r  )r   r  r)   rN   r]   rZ   rZ   r[   __fields_set__  s
    zBaseModel.__fields_set__:The `dict` method is deprecated; use `model_dump` instead.r   r   r   r   r   r   ztyping.Dict[str, Any])r   r   r   r   r   r   rV   c                C  s$   t jdtd | j||||||dS )Nr"  r  r#  )r   r  r)   r   )rX   r   r   r   r   r   r   rZ   rZ   r[   r   #  s    zBaseModel.dict?The `json` method is deprecated; use `model_dump_json` instead.)r   r   r   r   r   r   encodermodels_as_dictz"typing.Callable[[Any], Any] | None)
r   r   r   r   r   r   r%  r&  dumps_kwargsrV   c          
      K  sP   t jdtd |tk	rtd|tk	r.td|	r:td| j||||||dS )Nr$  r  zMThe `encoder` argument is no longer supported; use field serializers instead.zUThe `models_as_dict` argument is no longer supported; use a model serializer instead.z9`dumps_kwargs` keyword arguments are no longer supported.r#  )r   r  r)   r   r   r   )
rX   r   r   r   r   r   r   r%  r&  r'  rZ   rZ   r[   json8  s$     zBaseModel.jsonCThe `parse_obj` method is deprecated; use `model_validate` instead.)ra   r   rV   c                 C  s   t jdtd | |S )Nr)  r  r   r  r)   r   ra   r   rZ   rZ   r[   	parse_objX  s
     zBaseModel.parse_objThe `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, otherwise load the data then use `model_validate` instead.utf8)content_typeencodingprotoallow_picklezstr | bytes
str | NonezDeprecatedParseProtocol | None)ra   br/  r0  r1  r2  rV   c             
   C  s   t jdtd ddlm} z|j|||||d}W n ttfk
r } zldd l}	t	|t
r`d}
n&t	||	jrrd}
nt	|trd	}
nd
}
t|
t|d|d}tj| j|gW 5 d }~X Y nX | |S )Nr-  r  r   parser1  r/  r0  r2  r   zvalue_error.unicodedecodezvalue_error.jsondecodeZvalue_errorZ
type_error)Z__root__r   )r   r  r)   
deprecatedr6  Zload_str_bytesr   r   r(  rq   UnicodeDecodeErrorJSONDecodeErrorr   ZPydanticCustomErrorrs   r   r   r   r   )ra   r4  r/  r0  r1  r2  r6  r   r   r(  Ztype_strr   rZ   rZ   r[   	parse_raw`  s8    


$zBaseModel.parse_rawThe `parse_file` method is deprecated; load the data from file, then if your data is JSON use `model_validate_json`, otherwise `model_validate` instead.z
str | Path)ra   pathr/  r0  r1  r2  rV   c                C  s8   t jdtd ddlm} |j|||||d}| |S )Nr<  r  r   r5  r7  )r   r  r)   r8  r6  Z	load_filer,  )ra   r=  r/  r0  r1  r2  r6  r   rZ   rZ   r[   
parse_file  s    zBaseModel.parse_fileqThe `from_orm` method is deprecated; set `model_config['from_attributes']=True` and use `model_validate` instead.c                 C  s2   t jdtd | jdd s(tdd d| |S )Nr?  r  r   zHYou must set the config attribute `from_attributes=True` to use from_ormrQ   )r   r  r)   r<   ru   r#   r   r+  rZ   rZ   r[   from_orm  s     zBaseModel.from_ormDThe `construct` method is deprecated; use `model_construct` instead.c                 K  s"   t jdtd | jf d|i|S )NrB  r  rb   )r   r  r)   r   )ra   rb   rc   rZ   rZ   r[   	construct  s
     zBaseModel.constructThe `copy` method is deprecated; use `model_copy` instead. See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.)r   r   r   r   z+AbstractSetIntStr | MappingIntStrAny | Noneztyping.Dict[str, Any] | None)rX   r   r   r   r   rV   c             	   C  s  t jdtd ddlm} t|j| dd||ddf|p8i }| jdkrLd}ndd	 | j D }| j	dkrpd}nR| j	
 }t| j	D ]}	|	|kr||	 qt|D ]}	|	| j	kr||	||	< q|r| j| B }
n
t| j}
|r|
t|8 }
|j| ||
|||d
S )a  Returns a copy of the model.

        !!! warning "Deprecated"
            This method is now deprecated; use `model_copy` instead.

        If you need `include` or `exclude`, use:

        ```py
        data = self.model_dump(include=include, exclude=exclude, round_trip=True)
        data = {**data, **(update or {})}
        copied = self.model_validate(data)
        ```

        Args:
            include: Optional set or mapping specifying which fields to include in the copied model.
            exclude: Optional set or mapping specifying which fields to exclude in the copied model.
            update: Optional dictionary of field-value pairs to override field values in the copied model.
            deep: If True, the values of fields that are Pydantic models will be deep-copied.

        Returns:
            A copy of the model with included, excluded and updated fields as specified.
        rD  r  r   copy_internalsF)to_dictr   r   r   r   Nc                 S  s   i | ]\}}|t k	r||qS rZ   r   rf   rZ   rZ   r[   rj     s       z"BaseModel.copy.<locals>.<dictcomp>)r   )r   r  r)   r8  rF  r   _iterrO   rm   rM   r   listro   rN   r   rl   _copy_and_set_values)rX   r   r   r   r   rF  rc   r   rd   rh   rz   rZ   rZ   r[   r     sF    #     




zBaseModel.copyCThe `schema` method is deprecated; use `model_json_schema` instead.)r   r   rV   c                 C  s   t jdtd | j||dS )NrK  r  r   r   )r   r  r)   r(   )ra   r   r   rZ   rZ   r[   schema  s
     zBaseModel.schemaWThe `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.rL  )r   r   r'  rV   c                K  sB   t jdtd dd l}ddlm} |j| j||dfd|i|S )NrN  r  r   r   )pydantic_encoderrL  default)r   r  r)   r(  Zdeprecated.jsonrO  dumpsr(   )ra   r   r   r'  r(  rO  rZ   rZ   r[   schema_json$  s    zBaseModel.schema_jsonBThe `validate` method is deprecated; use `model_validate` instead.)ra   r}   rV   c                 C  s   t jdtd | |S )NrS  r  r*  )ra   r}   rZ   rZ   r[   validate:  s
     zBaseModel.validateLThe `update_forward_refs` method is deprecated; use `model_rebuild` instead.)localnsrV   c                 K  s*   t jdtd |rtd| jdd d S )NrU  r  z,`localns` arguments are not longer accepted.T)r   )r   r  r)   r   r   )ra   rV  rZ   rZ   r[   update_forward_refsB  s    zBaseModel.update_forward_refsHThe private method `_iter` will be removed and should no longer be used.)r   r   rV   c                 O  s,   t jdtd ddlm} |j| f||S )NrX  r  r   rE  )r   r  r)   r8  rF  rH  rX   r   r   rF  rZ   rZ   r[   rH  P  s    zBaseModel._iterWThe private method `_copy_and_set_values` will be removed and should no longer be used.c                 O  s,   t jdtd ddlm} |j| f||S )NrZ  r  r   rE  )r   r  r)   r8  rF  rJ  rY  rZ   rZ   r[   rJ  \  s    zBaseModel._copy_and_set_valuesMThe private method `_get_value` will be removed and should no longer be used.c                 O  s,   t jdtd ddlm} |j| f||S )Nr[  r  r   rE  )r   r  r)   r8  rF  
_get_value)ra   r   r   rF  rZ   rZ   r[   r\  i  s    zBaseModel._get_valueRThe private method `_calculate_keys` will be removed and should no longer be used.c                 O  s,   t jdtd ddlm} |j| f||S )Nr]  r  r   rE  )r   r  r)   r8  rF  _calculate_keysrY  rZ   rZ   r[   r^  w  s    zBaseModel._calculate_keys)N)N)N)[r   
__module____qualname____doc__r   TYPE_CHECKING__annotations___FieldrM   rN   rO   r=   r>   r   ZDecoratorInfosrD   rF   r   Z
MockValSerrJ   rI   	__slots__r!   r<   rB   rH   r\   Z__pydantic_base_init__r   r^   r_   classmethodr   r   r   r   r$   r%   r(   r   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r   ZRepresentationr  r  Z
__pretty____rich_repr__r  typing_extensionsr8  r  r!  r   r   r(  r,  r;  r>  rA  rC  r   rM  rR  rT  rW  rH  rJ  r\  r^  __classcell__rZ   rZ   r   r[   r+   B   s  
	P(8(37@ +7  &	"/	"G  	 			)	metaclass)
__config__ra  __base__r_  __validators____cls_kwargs__rs   zConfigDict | Noner3  rT   zdict[str, classmethod] | NonerL   r   r   )	__model_namerk  ra  rl  r_  rm  rn  field_definitionsrV   c                K  s   d S r   rZ   ro  rk  ra  rl  r_  rm  rn  rp  rZ   rZ   r[   r;     s    r;   )rk  ra  r_  rm  rn  z%type[Model] | tuple[type[Model], ...]r`   c                K  s   d S r   rZ   rq  rZ   rZ   r[   r;     s    )rk  ra  rl  r_  rm  rn  re  z,type[Model] | tuple[type[Model], ...] | Noneztuple[str, ...] | None)
ro  rk  ra  rl  r_  rm  rn  re  rp  rV   c                K  s  |dk	rt dt |dk	rB|dk	r0tdddt|tsV|f}nttjd t	f}|p\i }i }	i }
|
 D ]\}}t|st d| dt t|trtd	|}z|\}}W n0 tk
r } ztd
dd|W 5 d}~X Y nX nLt|r,t|^}}}ddlm} t||s6tdddn
d| }}|rD||
|< ||	|< qn|dkrltd}|jd }|
|d}|r|d|i |r|| ||	 |rt|j|d< t|}tj| ||d\}}}||k	r||d< || || ||fd|d|S )a2  Usage docs: https://docs.pydantic.dev/2.7/concepts/models/#dynamic-model-creation

    Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
    subclass of [`BaseModel`][pydantic.BaseModel].

    Args:
        __model_name: The name of the newly created model.
        __config__: The configuration of the new model.
        __doc__: The docstring of the new model.
        __base__: The base class or classes for the new model.
        __module__: The name of the module that the model belongs to;
            if `None`, the value is taken from `sys._getframe(1)`
        __validators__: A dictionary of methods that validate fields.
        __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.
        __slots__: Deprecated. Should not be passed to `create_model`.
        **field_definitions: Attributes of the new model. They should be passed in the format:
            `<name>=(<type>, <default value>)`, `<name>=(<type>, <FieldInfo>)`, or `typing.Annotated[<type>, <FieldInfo>]`.
            Any additional metadata in `typing.Annotated[<type>, <FieldInfo>, ...]` will be ignored.

    Returns:
        The new [model][pydantic.BaseModel].

    Raises:
        PydanticUserError: If `__base__` and `__config__` are both passed.
    Nz.__slots__ should not be passed to create_modelzFto avoid confusion `__config__` and `__base__` cannot be used togetherzcreate-model-config-baser@  r*   z3fields may not start with an underscore, ignoring "r   ztuple[str, Any]z4Field definitions should be a `(<type>, <default>)`.zcreate-model-field-definitionsr   )r8   z<Field definitions should be a Annotated[<type>, <FieldInfo>]r   )rc  r_  ra  r<   )kwds__orig_bases__F)Z#__pydantic_reset_parent_namespace__Z_create_model_module)r   r  RuntimeWarningr#   rq   r   r   castTyper+   rm   r   r   r   r   Zis_annotatedrh  get_argsfieldsr8   sys	_getframe	f_globalsr   r   r   Zconfig_dicttypesresolve_basesprepare_class)ro  rk  ra  rl  r_  rm  rn  re  rp  rx  r   f_nameZf_defZf_annotationZf_valueer  r8   f	namespaceresolved_basesmetansrr  rZ   rZ   r[   r;     s    %














)\ra  
__future__r   Z_annotationsr  ry  r|  r   r   r   r   r   r   r   r   r	   r
   r   r   r   r   rh  r   r   	_internalr   r   r   r   r   r   r   r   r   r   Z
_migrationr   aliasesr   r   Zannotated_handlersr   r    r   r!   errorsr"   r#   Zjson_schemar$   r%   r&   r'   r(   r)   r*   rs   r  r   r-   rc  rb  inspectr.   pathlibr/   r0   r1   r2   r3   Z_internal._utilsr4   r5   Zdeprecated.parser6   ZDeprecatedParseProtocolrx  r7   r8   r9   r:   rd  DeprecationWarning__all__Zobject_setattrrv   ZModelMetaclassr+   overloadr   r;   r   rZ   rZ   rZ   r[   <module>   s   ,02          M$$$u