U
    ={f                 	   @  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
Z
ddl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 ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ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+m,Z,m-Z- ddlm.Z. ddl/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZFmGZGmHZH ddlImJZJ ddlKmLZL ddlmMZM ddlNmOZOmPZPmQZQmRZRmSZS ddlTmUZUmVZV ddlWmXZXmYZY ddlOmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb ddlPmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZn ddlompZp ddlqmrZrmsZs dd ltmuZu dd!lvmwZwmxZxmyZymzZz dd"l{m|Z| dd#lSm}Z}m~Z~ dd$lmZ e rdd%lmZmZ dd&lmZ dd'lmZ dd(lmZ dd)lmZ dd*l{mZ e	jd+kZee5ed,f Ze+ejefeef Ze*d-ed.Ze+ecej ecef ecee f Ze?Ze"e!ege2j0f Zee
jgZd/ed0< ee
jejjgZd/ed1< ee
jejjgZd/ed2< ee
jejjgZd/ed3< ee
j#ejjejj(gZd/ed4< d5d6d7d8d9d:Zd;d<d=d>d?d@ZdAd6dBdCdDdEZdFdGdHdFdIdJdKZdLdMdNdOdPdQdRZe#e)e! eDf ZdSdNdTdTdUdVdWZe+e#ee!f df ZG dXdY dYZdNdNdNdZd[d\ZG d]d^ d^Zd_d` dad` dbd` dcd` ddd` ded` dfd` dgd` dhZdiedj< dFdkdHdFdldmdnZdod7dpdqdrZdFdsdtdFdudvdwZdxdFdFdydzd{ZdNdTd|d}d~dZdOdddddZdOddddZG dd de8ZdddddddFddHdddNddddZG dd dZdTdddddZG dd dZG dd dZdS )z-Convert python types to pydantic-core schema.    )annotationsN)	ExitStackcontextmanager)copydeepcopy)Enum)partial)	Parameter_ParameterKind	signature)chain)
attrgetter)FunctionType
LambdaType
MethodType)TYPE_CHECKINGAnyCallableDictFinal
ForwardRefIterableIteratorMappingTypeTypeVarUnioncastoverload)warn)
CoreSchemaPydanticUndefinedcore_schemato_jsonable_python)	AnnotatedLiteralTypeAliasType	TypedDictget_args
get_originis_typeddict   )AliasGenerator)GetCoreSchemaHandlerGetJsonSchemaHandler)
ConfigDictJsonDictJsonEncoder)PydanticSchemaGenerationErrorPydanticUndefinedAnnotationPydanticUserError)JsonSchemaValue)version_short)PydanticDeprecatedSince20   )_core_utils_decorators_discriminated_union_known_annotated_metadata_typing_extra)ConfigWrapperConfigWrapperStack)CoreMetadataHandlerbuild_metadata_dict)	CoreSchemaOrFieldcollect_invalid_schemasdefine_expected_missing_refsget_refget_type_refis_function_with_inner_schema%is_list_like_schema_with_items_schemasimplify_schema_referencesvalidate_core_schema)	DecoratorDecoratorInfosFieldSerializerDecoratorInfoFieldValidatorDecoratorInfoModelSerializerDecoratorInfoModelValidatorDecoratorInfoRootValidatorDecoratorInfoValidatorDecoratorInfoget_attribute_from_basesinspect_field_serializerinspect_model_serializerinspect_validator)extract_docstrings_from_cls)collect_dataclass_fieldsget_type_hints_infer_globalns)PydanticRecursiveRef)get_standard_typevars_maphas_instance_in_typerecursively_defined_type_refsreplace_types)CallbackGetCoreSchemaHandler)is_finalvaris_self_type)lenient_issubclass)ComputedFieldInfo	FieldInfo	BaseModel)Discriminator)FieldValidatorModes)StandardDataclass)GetJsonSchemaFunction)      {   FieldDecoratorInfoType)boundz
list[type]TUPLE_TYPES
LIST_TYPES	SET_TYPESFROZEN_SET_TYPES
DICT_TYPESFieldDecoratorInfostrbool)infofieldreturnc                 C  s,   d| j krdS | j D ]}||kr dS qdS )zCheck if field name is in validator fields.

    Args:
        info: The field info.
        field: The field name to check.

    Returns:
        `True` if field name is in validator fields, `False` otherwise.
    *TF)fields)rx   ry   Zv_field_name r}   b/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/pydantic/_internal/_generate_schema.py)check_validator_fields_against_field_nameq   s    

r   zIterable[AnyFieldDecorator]zIterable[str]None)
decoratorsr|   rz   c                 C  sf   t |}| D ]T}d|jjkrq|jjdkr,q|jjD ]*}||kr4td|j d|j dddq4qdS )	av  Check if the defined fields in decorators exist in `fields` param.

    It ignores the check for a decorator if the decorator has `*` as field or `check_fields=False`.

    Args:
        decorators: An iterable of decorators.
        fields: An iterable of fields name.

    Raises:
        PydanticUserError: If one of the field names does not exist in `fields` param.
    r{   Fz*Decorators defined with incorrect fields: .zO (use check_fields=False if you're inheriting from the model and intended this)zdecorator-missing-fieldcodeN)setrx   r|   Zcheck_fieldsr4   Zcls_refcls_var_name)r   r|   decry   r}   r}   r~   check_decorator_fields_exist   s    r   z+Iterable[Decorator[FieldDecoratorInfoType]]z'list[Decorator[FieldDecoratorInfoType]])validator_functionsry   rz   c                   s    fdd| D S )Nc                   s   g | ]}t |j r|qS r}   )r   rx   ).0r   ry   r}   r~   
<listcomp>   s      z8filter_field_decorator_info_by_field.<locals>.<listcomp>r}   )r   ry   r}   r   r~   $filter_field_decorator_info_by_field   s    r   core_schema.CoreSchemaz'list[Decorator[ValidatorDecoratorInfo]]
str | None)schemaeach_item_validators
field_namerz   c                 C  s   | d dkr$t | d ||| d< | S | d dkr`| d }d k	rt| d | ||| d |< nt| r| dd }|d krt }t|||| d< nP| d dkr| dd }|d krt }t|||| d< n|rtd	| d  | S )
Ntypenullabler   tuplevariadic_item_indexZitems_schemadictZvalues_schemazO`@validator(..., each_item=True)` cannot be applied to fields with a schema of )apply_each_item_validatorsgetapply_validatorsrH   r"   
any_schema	TypeError)r   r   r   r   inner_schemar}   r}   r~   r      s2    

  r   rB   r.   r   r5   )schema_or_fieldhandlerclsrz   c          	      C  s   ddl m} ddlm} || }||}d|krP|d }|  d|ig|d< d|krb|j|d< ||krndn|j}|rd|krt	||d< n&t
||r|jd	 jr|jd	 j|d< |S )
a0  Add title and description for model-like classes' JSON schema.

    Args:
        schema_or_field: The schema data to generate a JSON schema from.
        handler: The `GetCoreSchemaHandler` instance.
        cls: The model-like class.

    Returns:
        JsonSchemaValue: The updated JSON schema.
    r+   re   )	RootModelz$refZallOftitleNdescriptionroot)mainrf   
root_modelr   Zresolve_ref_schemaclear__name____doc__inspectcleandoc
issubclassmodel_fieldsr   )	r   r   r   rf   r   json_schemaoriginal_schemarefZ	docstringr}   r}   r~   modify_model_json_schema   s     

r   zJsonEncoders | Noner    )json_encoderstpr   rz   c                 C  s~   | s|S d|kr|S |ft |d|jjdd D ]F}| |}|dkrJq2tdt  dt tj	|dd|d< |  S |S )	a  Iterate over the json_encoders and add the first matching encoder to the schema.

    Args:
        json_encoders: A dictionary of types and their encoder functions.
        tp: The type to check for a matching encoder.
        schema: The schema to add the encoder to.
    serialization__mro__Nz=`json_encoders` is deprecated. See https://docs.pydantic.dev/z</concepts/serialization/#custom-serializers for alternativesjson)	when_used)
getattr	__class__r   r   warningsr   r6   r7   r"   $plain_serializer_function_ser_schema)r   r   r   baseencoderr}   r}   r~   ,_add_custom_serialization_from_json_encoders   s    
"
r   c                   @  sB   e Zd ZdZddddZeddddZed	d
ddZdS )TypesNamespaceStackzA stack of types namespaces.TypesNamespace)types_namespacec                 C  s   |g| _ d S N_types_namespace_stack)selfr   r}   r}   r~   __init__  s    zTypesNamespaceStack.__init__rz   c                 C  s
   | j d S Nr   r   r   r}   r}   r~   tail  s    zTypesNamespaceStack.tail	type[Any])for_typec                 c  s<   t || jpi }| j| z
d V  W 5 | j  X d S r   )r=   Zget_cls_types_namespacer   r   appendpop)r   r   r   r}   r}   r~   push   s
    
zTypesNamespaceStack.pushN)	r   
__module____qualname__r   r   propertyr   r   r   r}   r}   r}   r~   r     s   r   )abrz   c                 C  s   | dk	r| S |S )aB  Return the first argument if it is not None, otherwise return the second argument.

    Use case: serialization_alias (argument a) and alias (argument b) are both defined, and serialization_alias is ''.
    This function will return serialization_alias, which is the first argument, even though it is an empty string.
    Nr}   )r   r   r}   r}   r~   _get_first_non_null*  s    r   c                   @  s  e Zd ZdZdZddddddd	d
Zedddddd dddZeddddZ	eddddZ
ed dddZeddddZ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ddd d(d)Zddd*d+d,Zddd-d.d/Zdd0dd1d2d3ZG d4d5 d5eZddd6d7d8Zddd6d9d:Zdd;dd<d=d>Zdddd@dAdBdCZdDd@dEdFdGZddd6dHdIZdddJdKdLdMZddd-dNdOZeddPdQdRdSdTZ eddUd-dVdTZ ddddUdRdXdTZ ddd-dYdZZ!dd[d-d\d]Z"dd@d-d^d_Z#dd@d-d`daZ$ddddbdcddZ%d?dedfdgdhddidjdkdlZ&dfdgdhdmdndodpZ'dfdgdhdqdndrdsZ(e)dtdgdfddudvdwZ*e)dtdxdfdydzd{Z+dfdgdhd|dnd}d~Z,dd@dddZ-ddd-ddZ.dddddZ/ddd@dddZ0ddd@dddZ1e2j3dfdfdddddddZ4dd@dddZ5d@dddZ6dd@dddZ7dd@dddZ8dd@dddZ9dddddZ:dd@dddZ;d@dddZ<ddd@dddZ=d;ddddZ>dd@dddZ?ddddddZ@dd@dddZAddQddddZBddÄ fdddddƜddȄZCd@dd@dɜdd˄ZDd@dd@dɜdd̈́ZEdddddќddӄZFdd@ddd@d՜ddׄZGd@dd@dٜddۄZHdS )GenerateSchemaz\Generate core schema for a Pydantic model, dataclass and types like `str`, `datetime`, ... .)_config_wrapper_stackr   _typevars_mapfield_name_stackmodel_type_stackdefsNr>   zdict[str, Any] | Nonezdict[Any, Any] | Noner   )config_wrapperr   typevars_maprz   c                 C  s6   t || _t|| _|| _t | _t | _t	 | _
d S r   )r?   r   r   r   r   _FieldNameStackr   _ModelTypeStackr   _Definitionsr   )r   r   r   r   r}   r}   r~   r   ?  s    

zGenerateSchema.__init__r?   r   r   r   )config_wrapper_stacktypes_namespace_stackr   r   r   rz   c                 C  s4   |  | }||_||_||_||_t |_||_|S r   )__new__r   r   r   r   r   r   r   )r   r   r   r   r   r   objr}   r}   r~   Z__from_parentM  s    	
zGenerateSchema.__from_parentr   c                 C  s   | j jS r   )r   r   r   r}   r}   r~   _config_wrapper_  s    zGenerateSchema._config_wrapperc                 C  s   | j jS r   )r   r   r   r}   r}   r~   _types_namespacec  s    zGenerateSchema._types_namespacec                 C  s(   | j jp
t}|| j| j| j| j| jS r   )	r   Zschema_generatorr   _GenerateSchema__from_parentr   r   r   r   r   )r   r   r}   r}   r~   _current_generate_schemag  s    z'GenerateSchema._current_generate_schemarw   c                 C  s   | j jS r   )r   Zarbitrary_types_allowedr   r}   r}   r~   _arbitrary_typesr  s    zGenerateSchema._arbitrary_typesr    c                 C  s   t  S )zGenerate a CoreSchema for `str`)r"   
str_schemar   r}   r}   r~   r   v  s    zGenerateSchema.str_schemar   )r   
items_typerz   c                 C  s   t | |S r   )r"   list_schemagenerate_schemar   r   r   r}   r}   r~   _list_schema|  s    zGenerateSchema._list_schema)r   	keys_typevalues_typerz   c                 C  s   t | || |S r   )r"   Zdict_schemar   )r   r   r   r   r}   r}   r~   _dict_schema  s    zGenerateSchema._dict_schemac                 C  s   t | |S r   )r"   Z
set_schemar   r   r}   r}   r~   _set_schema  s    zGenerateSchema._set_schemac                 C  s   t | |S r   )r"   Zfrozenset_schemar   r   r}   r}   r~   _frozenset_schema  s    z GenerateSchema._frozenset_schemar   rz   c                 C  s,   t |ts"t|dt t S t|S )Na   is not a Python type (it may be an instance of an object), Pydantic will allow any object with no validation since we cannot even enforce that the input is an instance of the given type. To get rid of this error wrap the type with `pydantic.SkipValidation`.)
isinstancer   r   UserWarningr"   r   is_instance_schema)r   r   r}   r}   r~   _arbitrary_type_schema  s    
z%GenerateSchema._arbitrary_type_schemar   rz   c                 C  s   t d|dd S )N,Unable to generate pydantic-core schema for a  . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.)r2   r   r   r}   r}   r~   _unknown_type_schema  s    
z#GenerateSchema._unknown_type_schemazstr | Discriminator | None)r   discriminatorrz   c                 C  sF   |d kr|S zt ||W S  t jk
r@   t || | Y S X d S r   )r;   Zapply_discriminatorZMissingDefinitionForUnionRefZset_discriminator_in_metadata)r   r   r   r}   r}   r~   _apply_discriminator_to_union  s    z,GenerateSchema._apply_discriminator_to_unionc                   @  s   e Zd ZdS )zGenerateSchema.CollectedInvalidN)r   r   r   r}   r}   r}   r~   CollectedInvalid  s   r  r   rz   c                 C  s8   |  |}t|}t|r"|  t|}t|}|S r   )collect_definitionsrI   rC   r  r;   Zapply_discriminatorsrJ   r   r   r}   r}   r~   clean_schema  s    

zGenerateSchema.clean_schemac                 C  sP   t d|dd }|r"|| jj|< d|kr8t|d }t|t| jj S )Nr   r   )	r   r   r   definitionsr"   definition_reference_schemaZdefinitions_schemalistvalues)r   r   r   r}   r}   r~   r    s    z"GenerateSchema.collect_definitionszCallable[..., Any])metadata_schemajs_functionrz   c                 C  s,   t |j}|dg }||kr(|| d S )Npydantic_js_functions)r@   metadata
setdefaultr   )r   r
  r  r  r  r}   r}   r~   _add_js_function  s    
zGenerateSchema._add_js_functionTr   )r   from_dunder_get_core_schemarz   c                 C  sv   d}|r |  ||}|dk	r |}|dkr2| |}t||}|dk	rbt|| jj}|rb| || t| jj	||}|S )a  Generate core schema.

        Args:
            obj: The object to generate core schema for.
            from_dunder_get_core_schema: Whether to generate schema from either the
                `__get_pydantic_core_schema__` function or `__pydantic_core_schema__` property.

        Returns:
            The generated core schema.

        Raises:
            PydanticUndefinedAnnotation:
                If it is not possible to evaluate forward reference.
            PydanticSchemaGenerationError:
                If it is not possible to generate pydantic-core schema.
            TypeError:
                - If `alias_generator` returns a disallowed type (must be str, AliasPath or AliasChoices).
                - If V1 style validator with `each_item=True` applied on a wrong field.
            PydanticUserError:
                - If `typing.TypedDict` is used instead of `typing_extensions.TypedDict` on Python < 3.12.
                - If `__modify_schema__` method is used instead of `__get_pydantic_json_schema__`.
        N)
_generate_schema_from_property_generate_schema_inner!_extract_get_pydantic_json_schemaresolve_original_schemar   r  r  r   r   r   )r   r   r  r   from_propertymetadata_js_functionr
  r}   r}   r~   r     s    

zGenerateSchema.generate_schemaztype[BaseModel])r   rz   c                   s  j |\}}|dk	r,|W  5 Q R  S |j}|j  j}tt j  j	  j
 | |  t|jdd}||}ttt|dgd} j }	d}
|ddkrz|jd |kst|jd	 tkst|jdd	 D ]}t|d
i dd}|dk	rt|tr0ttj|dddj}t|}|tt fkrNt!dj"|ddd }|t#k	r$|}
 qzqj%&|r j'&|X j(|j)r*d|d  }|d }t+||	d}t,j-||t|dddt|dd|||d}nt,j. fdd|/ D  fdd| D |
|j0d}t1| j2 d}t3|t4 }|dk	rb|}t+||	d}t,j-||t|dddt|dd|||d}5| j6 }t+||	d}|j j7|< t,8|W  5 Q R  W  5 Q R  W  5 Q R  S Q R X W 5 Q R X W 5 Q R X dS )z%Generate schema for a Pydantic model.NF)checkr   js_functionsZextra_fields_behaviorallowr   r   __annotations__Z__pydantic_extra__T)is_argumentZis_classzEThe type annotation for `__pydantic_extra__` must be `Dict[str, ...]`requiredr8   r   r   innerZ__pydantic_custom_init__Z__pydantic_post_init__)Zcustom_initr   	post_initconfigr   r  c                   s    i | ]\}}| || qS r}   )_generate_md_field_schemar   kvr   r   r}   r~   
<dictcomp>D  s      z0GenerateSchema._model_schema.<locals>.<dictcomp>c                   s   g | ]} | jqS r}   _computed_field_schemafield_serializersr   dr'  r}   r~   r   E  s   z0GenerateSchema._model_schema.<locals>.<listcomp>)computed_fieldsextras_schemaZ
model_nameouter)9r   get_schema_or_refr   __pydantic_decorators__r.  r   r   field_validatorsr	  r+  
validatorskeysr>   Zmodel_configcore_configrA   r   r   model_validatorsr   r   AssertionErrorobjectr   r   rv   r=   eval_type_backportZ_make_forward_refr   r)   r   r   r2    _get_args_resolving_forward_refsr   r   r   r   r   r   Z__pydantic_root_model___common_field_schemaapply_model_validatorsr"   model_schemaZmodel_fields_schemaitemsr   r   root_validatorsrD   r]   _apply_model_serializersmodel_serializersr  r  )r   r   Z	model_refmaybe_schemar|   r.  r   r6  r  r7  r/  Zcandidate_clsZextras_annotationr   Zextra_items_typeZ
root_fieldr   r>  Zfields_schemaZnew_inner_schemar   r}   r'  r~   _model_schema  s    


 

	


zGenerateSchema._model_schemac                   sH   ddddd |d dkrD| j j fdd	|d D  |d
 }|S )zuUnpack all 'definitions' schemas into `GenerateSchema.defs.definitions`
        and return the inner schema.
        r    rv   )srz   c                 S  s   | d S )Nr   r}   )rE  r}   r}   r~   rE   g  s    z1GenerateSchema._unpack_refs_defs.<locals>.get_refr   r  c                   s   i | ]} ||qS r}   r}   )r   rE  rE   r}   r~   r(  k  s      z4GenerateSchema._unpack_refs_defs.<locals>.<dictcomp>r   )r   r  updater  r}   rF  r~   _unpack_refs_defsb  s
     z GenerateSchema._unpack_refs_defszcore_schema.CoreSchema | None)r   sourcerz   c              
   C  sd  t |r| j }| j|"\}}|dk	r<|W  5 Q R  S W 5 Q R X ||krTd}nd}t|dd }dk	rtt|j	dkr||}n||t
| j| |d}nft|dd }dk	r|dd|kr|}n<t|d	d }	dk	rtd
t tdd |	 D }ndS | |}t|r<|d dd}
|
rD|
|d< nt|}
|
r`|| jj|
< t|
S |S )a0  Try to generate schema from either the `__get_pydantic_core_schema__` function or
        `__pydantic_core_schema__` property.

        Note: `__get_pydantic_core_schema__` takes priority so it can
        decide whether to use a `__pydantic_core_schema__` attribute, or generate a fresh schema.
        Nunpackzto-def__get_pydantic_core_schema__r8   )ref_modeZ__pydantic_core_schema__r   Z__get_validators__zc`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.c                 S  s   g | ]}t |qS r}   r"   Z"with_info_plain_validator_functionr   r&  r}   r}   r~   r     s     zAGenerateSchema._generate_schema_from_property.<locals>.<listcomp>r   r   )ra   r   r   r   r1  r   lenr   r   
parametersr_   r  r   r7   r"   chain_schemarH  rG   r   rE   r  r  )r   r   rI  _rC  rL  Z
get_schemar   Zexisting_schemar4  r   r}   r}   r~   r  o  sN    

  



z-GenerateSchema._generate_schema_from_propertyc              
   C  sv   zt j|| jd}W n. tk
rB } zt||W 5 d }~X Y nX t|tr`t|jd| | j	rrt
|| j	}|S )N)globalnsz%Unable to evaluate forward reference )r=   r:  r   	NameErrorr3   from_name_errorr   r   __forward_arg__r   r^   )r   r   er}   r}   r~   _resolve_forward_ref  s    
z#GenerateSchema._resolve_forward_refzLiteral[True]ztuple[Any, ...])r   r  rz   c                 C  s   d S r   r}   )r   r   r  r}   r}   r~   r;    s    z/GenerateSchema._get_args_resolving_forward_refsztuple[Any, ...] | Nonec                 C  s   d S r   r}   r   r}   r}   r~   r;    s    Fc                   s<   t |}|r$t fdd|D }n|r8td| d|S )Nc                   s$   g | ]}t |tr |n|qS r}   )r   r   rX  )r   r   r   r}   r~   r     s     zCGenerateSchema._get_args_resolving_forward_refs.<locals>.<listcomp>z	Expected z+ to have generic parameters but it had none)r(   r   r   )r   r   r  argsr}   r   r~   r;    s    c                 C  s   |  |}|stS |d S )Nr   )r;  r   )r   r   rY  r}   r}   r~   _get_first_arg_or_any  s    
z$GenerateSchema._get_first_arg_or_anyztuple[Any, Any]c                 C  sJ   |  |}|sttfS t|dk r:t|}td| d|d |d fS )Nr+   z Expected two type arguments for z, got 1r   r8   )r;  r   rO  r)   r   )r   r   rY  originr}   r}   r~   _get_first_two_args_or_any  s    
z)GenerateSchema._get_first_two_args_or_anyc              
   C  s   t |tr| |S t |tr"|S t |tr4t|}t |trN| | |S ddlm	} t
||r| j| | |W  5 Q R  S Q R X t |trtj|jdS | |S )Nr+   re   )
schema_ref)r   _AnnotatedType_annotated_schemar   rv   r   r   rX  r   rf   rb   r   r   rD  rZ   r"   r  Ztype_ref
match_type)r   r   rf   r}   r}   r~   r    s    






z%GenerateSchema._generate_schema_innerc                 C  s  |t kr|  S |tkr t S |tkr0t S |tkr@t S |t	krPt
 S |tks`|tkrht S |dksz|tjkrt S |tkr| |S |tkr| || |S |tkr| || |S |tk r| || |S |tkr| j|f| | S t|tr| |S |t kr,| ! S t"|r@t# S t$|rV| %|S t&|rl| '|dS t(|r| )|dS t*|r| +|j,S |t-j.kr| /|S |t0j1j2ks|t3j2kr| 4 S t|t3j5r| 6|S t7|r|t8krt S | +| |S t|t9t:t;t<fr6| =|S t>?|rht@|tArhddlBmC} ||| jDjES tF|r| G|dS | H|d}|dk	r|\}}| I||S tJ|}|dk	r| K||S | jLr| M|S | N|S )a  Main mapping of types to schemas.

        The general structure is a series of if statements starting with the simple cases
        (non-generic primitive types) and then handling generics and other more complex cases.

        Each case either generates a schema directly, calls into a public user-overridable method
        (like `GenerateSchema.tuple_variable_schema`) or calls into a private method that handles some
        boilerplate before calling into the user-facing method (e.g. `GenerateSchema._tuple_schema`).

        The idea is that we'll evolve this into adding more and more user facing methods over time
        as they get requested and we figure out what the right API for them is.
        Nr8   )get_enum_core_schemar}   )Orv   r   bytesr"   Zbytes_schemaintZ
int_schemafloatZfloat_schemarw   Zbool_schemar   r9  r   r=   NoneTypeZnone_schemarp   _tuple_schemarq   r   rZ  rr   r   rs   r   rt   r   r\  r   r&   _type_alias_type_schemar   _type_schemaZis_callable_typeZcallable_schemaZis_literal_type_literal_schemar*   _typed_dict_schemais_namedtuple_namedtuple_schemaZis_new_typer   __supertype__rePattern_pattern_schemacollectionsabcHashabletyping_hashable_schemar   _unsubstituted_typevar_schemar`   r   r   r   r   r   _callable_schemar   isclassr   r   _std_types_schemara  r   config_dictis_dataclass_dataclass_schema0_get_prepare_pydantic_annotations_for_known_type_apply_annotationsr)   _match_generic_typer   r   r   )r   r   ra  ressource_typer   r[  r}   r}   r~   r`    s    














zGenerateSchema.match_type)r   r[  rz   c                 C  s  t |tr| |S t|r*| ||S t|r@| ||S | ||}|d k	rX|S t	|rl| 
|S |tkr~| |S |tkr| || |S |tkr| || |S |tkr| || |S |tkr| j|f| | S t|r | ||S |tjtfkr| |S |tjtjjhkr8|  |S |tj!tjj!tj"tjj"hkr`| #|S |t$j%tj%fkr|| &|S | j'r| (|S | )|S r   )*r   r&   rg  r=   r{  r|  rk  rl  r  origin_is_union_union_schemarp   rf  rq   r   rZ  rr   r   rs   r   rt   r   r\  r*   rj  rt  r   r   _subclass_schemaSequencerq  rr  _sequence_schemar   	Generator_iterable_schemarn  ro  rp  r   r   r   )r   r   r[  r  r}   r}   r~   r  N  sD    












z"GenerateSchema._match_generic_typer  rv   rd   rL   zcore_schema.TypedDictField)name
field_infor   r  rz   c                C  sD   |  |||}tj|d | s$dn||d |d |d |d dS )zAPrepare a TypedDictField to represent a model or typeddict field.r   Fserialization_excludevalidation_aliasserialization_aliasr  )r  r  r  r  r  )r<  r"   Ztyped_dict_fieldis_required)r   r  r  r   r  common_fieldr}   r}   r~   _generate_td_field_schemaz  s    	z(GenerateSchema._generate_td_field_schemazcore_schema.ModelField)r  r  r   rz   c                 C  s<   |  |||}tj|d |d |d |d |d |d dS )z0Prepare a ModelField to represent a model field.r   r  r  r  frozenr  r  r  r  r  r  )r<  r"   Zmodel_fieldr   r  r  r   r  r}   r}   r~   r#    s    z(GenerateSchema._generate_md_field_schemazcore_schema.DataclassFieldc                 C  sV   |  |||}tj||d |j|jp&d|jr0dnd|d |d |d |d |d d	
S )
zJPrepare a DataclassField to represent the parameter/field, of a dataclass.r   NFr  r  r  r  r  )initZ	init_onlykw_onlyr  r  r  r  r  )r<  r"   Zdataclass_fieldr  Zinit_varr  r  r}   r}   r~   _generate_dc_field_schema  s    z(GenerateSchema._generate_dc_field_schemaz%Callable[[str], str] | AliasGenerator)alias_generatorr  r   rz   c                 C  s  |j dks4|j dks4|jdks4|jdks4|jdkrd\}}}t| trZ| |\}}}n2t| tr| |}t|tst	d|  d|j
 |j dks|j dkrd|_ |j dkrt|||_t|||_||_|jdkr||_|jdkrt|||_|jdkrt|||_dS )a  Apply an alias_generator to aliases on a FieldInfo instance if appropriate.

        Args:
            alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance.
            field_info: The FieldInfo instance to which the alias_generator is (maybe) applied.
            field_name: The name of the field from which to generate the alias.
        Nr8   NNNalias_generator  must return str, not )alias_priorityaliasr  r  r   r,   generate_aliasesr   rv   r   r   r   )r  r  r   r  r  r  r}   r}   r~   $_apply_alias_generator_to_field_info  s:    






z3GenerateSchema._apply_alias_generator_to_field_inforc   r  computed_field_infocomputed_field_namec                 C  s   |j dks|j dks|jdkrd\}}}t| trD| |\}}}n2t| trv| |}t|tsvtd|  d|j |j dks|j dkrd|_ |j dkrt	|||_dS )a  Apply an alias_generator to alias on a ComputedFieldInfo instance if appropriate.

        Args:
            alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance.
            computed_field_info: The ComputedFieldInfo instance to which the alias_generator is (maybe) applied.
            computed_field_name: The name of the computed field from which to generate the alias.
        Nr8   r  r  r  )
r  r  r   r,   r  r   rv   r   r   r   )r  r  r  r  r  r  r}   r}   r~   -_apply_alias_generator_to_computed_field_info  s"    




z<GenerateSchema._apply_alias_generator_to_computed_field_info_CommonFieldc              	     s  ddl m}m} ddlm} tjttfrԈj	}j
r^|p>i  }|dd j
 D  tj|}|jk	rt|ts||}	|	j_|	j D ](\}
}|
jkr|
jkrt|
| q|	jj_jj }}dddfdd	}j|0 jd k	r$j|||d
}n||}W 5 Q R X t|j |}t|rZd_dd |D   fdd|D }t| |}t |t|||}t |t|j! ||}" st#|}$|t|j% |}j&j't(j)pj)dkpd t*j+d}dd | D }j,}t-t.||gd}j/j0}|d k	rV1|| t2j3||frtj34 }nj3}t5|j6rdnd |j7j8|dS )Nr+   )AliasChoices	AliasPathrd   c                 S  s   i | ]\}}|j |qS r}   )r   r$  r}   r}   r~   r(    s      z7GenerateSchema._common_field_schema.<locals>.<dictcomp>r    r  c                   s    |  j} | S r   )r   r   r   )r  r   r}   r~   set_discriminator1  s    z>GenerateSchema._common_field_schema.<locals>.set_discriminator)transform_inner_schemaTc                 S  s   g | ]}|j jd kr|qS )T)rx   Z	each_itemrN  r}   r}   r~   r   E  s      z7GenerateSchema._common_field_schema.<locals>.<listcomp>c                   s   g | ]}| kr|qS r}   r}   rN  )r   r}   r~   r   F  s       )r   r   
deprecatedexamplesc                 S  s   i | ]\}}|d k	r||qS r   r}   r$  r}   r}   r~   r(  ]  s       Zjs_annotation_functionsr  )9r  r  r  r|   rd   r\   
annotationr   rv   r   r   r   rG  r?  r=   eval_type_lenientrZ   from_annotationZ_attributes_setZmetadata_lookupsetattrr  r   r   r   r~  r   r4  r	  $_validators_require_validate_defaultvalidate_defaultr   r   r3  r  wrap_default_apply_field_serializersr+  r   r   rw   r  r#   r  json_schema_extrarA   get_json_schema_update_funcr   r  r  r   r  Zconvert_to_aliases_common_fieldexcluder  r  )r   r  r  r   r  r  rd   r   Z	evaluatedZnew_field_infor%  r&  r  r   r  r   Zthis_field_validatorsZjson_schema_updatesr  r  r  r  r}   )r   r  r   r~   r<    s    
	
  

 

z#GenerateSchema._common_field_schema)
union_typerz   c           
      C  s   | j |dd}g }d}|D ],}|dks0|tjkr6d}q|| | qt|dkr^|d }nNg }|D ]:}|di tj}	|	dk	r|||	f qf|| qft	
|}|rt	|}|S )zGenerate schema for a Union.Tr  FNr8   r   r  )r;  r=   re  r   r   rO  r   r9   ZTAGGED_UNION_TAG_KEYr"   union_schemaZnullable_schema)
r   r  rY  choicesr   argrE  Zchoices_with_tagschoicetagr}   r}   r~   r  w  s&    


zGenerateSchema._union_schemac              
   C  s   | j |\}}|d k	r*|W  5 Q R  S t|p4|}|j}t|}| j|@ t|| j	}t
||}| |}|d dkst||d< W 5 Q R X || j j|< t|W  5 Q R  S Q R X d S )Nr   r  r   )r   r1  r)   Z	__value__r[   r   r   r=   r  r   r^   r   r8  r  r"   r  )r   r   r   rC  r[  r  r   r   r}   r}   r~   rg    s    

z&GenerateSchema._type_alias_type_schema)literal_typerz   c                 C  s&   t |}|std| t|S )zGenerate schema for a Literal.z(literal "expected" cannot be empty, obj=)r=   Zall_literal_valuesr8  r"   Zliteral_schema)r   r  expectedr}   r}   r~   ri    s    
zGenerateSchema._literal_schema)typed_dict_clsr[  rz   c                   s  ddl m} j| j|n\}}|dk	rT|W  5 Q R  W  5 Q R  S t|}|dk	rh|}tst|j	dkrt
dddzt|d}W n tk
r   d}Y nX j| j| j|}j|j}	i }
t| jjrt|d	d
}nd}t|jd	d D ]\}}t||}||	k}t|tjkrfd	}j|d	dd }n&t|tjkrd}j|d	dd }| |}|dk	r|j!dkr||kr|| |_!j"|| |d|
|< q$t#t$t%|dg|d}t&j'|
 fdd j() D |||d}*| j+) }t,| j-) d}|jj.|< t&/|W  5 Q R  W  5 Q R  W  5 Q R  W  5 Q R  S Q R X W 5 Q R X W 5 Q R X W 5 Q R X dS )a  Generate schema for a TypedDict.

        It is not possible to track required/optional keys in TypedDict without __required_keys__
        since TypedDict.__new__ erases the base classes (it replaces them with just `dict`)
        and thus we can track usage of total=True/False
        __required_keys__ was added in Python 3.9
        (https://github.com/miss-islington/cpython/blob/1e9939657dd1f8eb9f596f77c1084d2d351172fc/Doc/library/typing.rst?plain=1#L1546-L1548)
        however it is buggy
        (https://github.com/python/typing_extensions/blob/ac52ac5f2cb0e00e7988bae1e2a1b8257ac88d6d/src/typing_extensions.py#L657-L666).

        On 3.11 but < 3.12 TypedDict does not preserve inheritance information.

        Hence to avoid creating validators that do not do what users expect we only
        support typing.TypedDict on Python >= 3.12 or typing_extension.TypedDict on all versions
        r+   r  Nrt  zXPlease use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.ztyped-dict-versionr   __pydantic_config__T)Zuse_inspect)localnsinclude_extrasr  r   Fr  )r  r  c                   s   g | ]} | jqS r}   r)  r,  r'  r}   r~   r   
  s   z5GenerateSchema._typed_dict_schema.<locals>.<listcomp>)r.  r   r  r"  all)0r|   rd   r   r   r   r1  r[   _SUPPORTS_TYPEDDICTr   r   r4   rS   AttributeErrorr   r   r   r6  r   Z__required_keys__rL   buildZuse_attribute_docstringsrW   rY   r   r?  r^   r)   r=   ZRequiredr;  ZNotRequiredr  r   r  rA   r   r   r"   Ztyped_dict_schemar.  r	  rA  rB  r=  r7  r  r  )r   r  r[  rd   Ztyped_dict_refrC  r   r"  r6  Zrequired_keysr|   Zfield_docstringsr   r  r  r  r  Z	td_schemar   r}   r'  r~   rj    s     
 

  


    z!GenerateSchema._typed_dict_schema)namedtuple_clsr[  rz   c                   s   j   j \}}|dk	rD|W  5 Q R  W  5 Q R  S t |dk	rX| t djd}|s|dd  jD }rfdd| D }t	j
 fdd| D tdd	d
}t	j| |dW  5 Q R  W  5 Q R  S Q R X W 5 Q R X dS )z!Generate schema for a NamedTuple.NT)r  r  c                 S  s   i | ]
}|t qS r}   )r   )r   r%  r}   r}   r~   r(  )  s      z5GenerateSchema._namedtuple_schema.<locals>.<dictcomp>c                   s   i | ]\}}|t | qS r}   r^   r   r   r  r   r}   r~   r(  ,  s    c              	     s,   g | ]$\}}j || j|tjd qS ))default)_generate_parameter_schema_field_defaultsr   r	   emptyr  )r  r   r}   r~   r   2  s     z5GenerateSchema._namedtuple_schema.<locals>.<listcomp>)Zjs_prefer_positional_arguments)r  )r   )r   r   r   r1  r[   rY   r   _fieldsr?  r"   arguments_schemarA   call_schema)r   r  r[  Znamedtuple_refrC  r   r  r}   )r  r   r   r~   rl    s4      
	z!GenerateSchema._namedtuple_schemar   zLLiteral[('positional_only', 'positional_or_keyword', 'keyword_only')] | Nonezcore_schema.ArgumentsParameter)r  r  r  moderz   c              	   C  s   ddl m} |tjkr"||}n|||}|jdk	s@td|j|j }}| j	
| | ||}	W 5 Q R X | st||	}	t||	}
|dk	r||
d< |jdk	r|j|
d< nB| jj}t|tr|jdk	r|||
d< nt|tr|||
d< |
S )zXPrepare a ArgumentsParameter to represent a field in a namedtuple or function signature.r+   r  Nz<field.annotation should not be None when generating a schemar  r  )r|   rd   r	   r  r  Zfrom_annotated_attributer  r8  r  r   r   r~  r  r  r"   Zarguments_parameterr  r   r  r   r,   r   )r   r  r  r  r  rd   ry   r  r   r   Zparameter_schemar  r}   r}   r~   r  <  s*    



z)GenerateSchema._generate_parameter_schema)
tuple_typerz   c                   s   t | |}r0|r0tfdd|D }|s\|tkrPtjt gddS tg S nv|d tkrt|dkrtj 	|d gddS t
dn:t|dkr|d d	krtg S t fd
d|D S dS )zIGenerate schema for a Tuple, e.g. `tuple[int, str]` or `tuple[int, ...]`.c                 3  s   | ]}t | V  qd S r   r  r   paramr  r}   r~   	<genexpr>f  s     z/GenerateSchema._tuple_schema.<locals>.<genexpr>r   )r   r   r+   z&Variable tuples can only have one typer8   r}   c                   s   g | ]}  |qS r}   )r   r  r   r}   r~   r   {  s     z0GenerateSchema._tuple_schema.<locals>.<listcomp>N)r[   r;  r   rp   r"   Ztuple_schemar   EllipsisrO  r   
ValueError)r   r  paramsr}   )r   r   r~   rf  _  s    


zGenerateSchema._tuple_schemac                 C  s   t jt tdddS )NZis_typezInput should be a typeZcustom_error_typeZcustom_error_message)r"   custom_error_schemar   r   r   r}   r}   r~   rh  }  s
    zGenerateSchema._type_schemac                   s&    j |dd}t fdd|D S )z*Generate schema for `Type[Union[X, ...]]`.Tr  c                   s   g | ]}  tj| qS r}   r   rt  r   )r   rY  r   r}   r~   r     s     z<GenerateSchema._union_is_subclass_schema.<locals>.<listcomp>)r;  r"   r  )r   r  rY  r}   r   r~   _union_is_subclass_schema  s    z(GenerateSchema._union_is_subclass_schema)type_rz   c                   s     |}|tkr  S t|tjr~|jrTtt	|jrH 
|jS t|jS |jrtt fdd|jD S   S n"tt	|r 
|S t|S dS )z-Generate schema for a Type, e.g. `Type[int]`.c                   s   g | ]}  tj| qS r}   r  )r   cr   r}   r~   r     s     z3GenerateSchema._subclass_schema.<locals>.<listcomp>N)rZ  r   rh  r   rt  r   	__bound__r=   r  r)   r  r"   Zis_subclass_schema__constraints__r  )r   r  Z
type_paramr}   r   r~   r    s     


zGenerateSchema._subclass_schema)sequence_typerz   c           	      C  s   ddl m} | |}| |}t|}tjtjdd}|t	krdddl
m} t|t||g}tj||dd}tj|||dS )	z5Generate schema for a Sequence, e.g. `Sequence[int]`.r8   )serialize_sequence_via_listr  )Zcls_repr)sequence_validatorT)r   info_arg)r   python_schemar   )ry  r  rZ  r   r"   r   r   rt  r  r   _validatorsr  rQ  no_info_wrap_validator_function#wrap_serializer_function_ser_schemaZjson_or_python_schema)	r   r  r  	item_typeZitem_type_schemar   r  r  r   r}   r}   r~   r    s(    


    zGenerateSchema._sequence_schemazcore_schema.GeneratorSchemac                 C  s   |  |}t| |S )z$Generate a schema for an `Iterable`.)rZ  r"   Zgenerator_schemar   )r   r  r  r}   r}   r~   r    s    
zGenerateSchema._iterable_schema)pattern_typerz   c                 C  s   ddl m} tdd gd}tjtddt d}|tjksH|t	jkrZtj
|j||d	S | j|d
dd }|tkrtj
|j||d	S |tkrtj
|j||d	S td|dd S )Nr8   )r  c                 S  s
   dddS )Nstringregex)r   formatr}   )_1_2r}   r}   r~   <lambda>      z0GenerateSchema._pattern_schema.<locals>.<lambda>r  patternr   )r   return_schema)r   r  Tr  r   r   r   )r  r  rA   r"   r   r   r   rt  ro  rn   no_info_plain_validator_functionZpattern_either_validatorr;  rv   Zpattern_str_validatorrb  Zpattern_bytes_validatorr2   )r   r  r  r  Zserr  r}   r}   r~   rp    s@            zGenerateSchema._pattern_schemac                 C  s   t jt tjjdddS )NZis_hashablezInput should be hashabler  )r"   r  r   rq  rr  rs  r   r}   r}   r~   ru    s
    zGenerateSchema._hashable_schemaztype[StandardDataclass]ztype[StandardDataclass] | None)	dataclassr[  rz   c                   s  j | j|\}}|dk	rH|W  5 Q R  W  5 Q R  S t|}|dk	r\|}t 0}|jD ] }t|rl|	j
| qlt|jD ],}t|rt|dd}|	j| qj|}	jddlm}
 |
|rt|j}|r.| D ]}||j qnt|j|d}jjjdkrr| D ]*\}}|jdkrFtd| d	d
dqF|jdpt | t! fdd| D dd d}t"|d}t"|d}t#j$|j%| fdd j& D |d}t'| j( d} j) }t*||d}t#j+||||dd t,|D ||	d}-| j. }t*||d}|jj/|< t#0|W  5 Q R  W  5 Q R  W  5 Q R  S Q R X dst1dW 5 Q R X W 5 Q R X dS )z Generate schema for a dataclass.Nr  r+   )is_pydantic_dataclassr  r  FzField zd has `init=False` and dataclass has config setting `extra="allow"`. This combination is not allowed.z dataclass-init-false-extra-allowr   r2  c                 3  s    | ]\}} || V  qd S r   )r  r$  r'  r}   r~   r    s     z3GenerateSchema._dataclass_schema.<locals>.<genexpr>c                 S  s   |  ddk	S )Nr  Fr   )r   r}   r}   r~   r    r  z2GenerateSchema._dataclass_schema.<locals>.<lambda>)key__post_init__	__slots__c                   s   g | ]} | jqS r}   r)  r,  r'  r}   r~   r   #  s   z4GenerateSchema._dataclass_schema.<locals>.<listcomp>)r.  Zcollect_init_onlyr   c                 S  s   g | ]
}|j qS r}   )r  )r   ry   r}   r}   r~   r   4  s     )r!  r   r|   slotsr"  r0  ZUnreachable)2r   r   r   r1  r[   r   r   dataclassesr{  enter_contextr   reversedr   r   r   r6  r   r  r   Z__pydantic_fields__r	  Zapply_typevars_mapr   rX   r   extrar?  r  r4   __dict__r   rL   r  sortedhasattrr"   Zdataclass_args_schemar   r.  r   r@  r7  r=  Zdataclass_schemar|   rA  rB  r  r  r8  )r   r  r[  Zdataclass_refrC  r   Zdataclass_bases_stackZdataclass_baser"  r6  r  r|   ry   r   rY  has_post_initZ	has_slotsZargs_schemar   r7  Z	dc_schemar   r}   r'  r~   r|    s     











	4z GenerateSchema._dataclass_schemazcore_schema.CallSchema)functionrz   c                 C  s  t |}t|}tjdtjdtjdi}g }d}d}|j D ]\}}	|	j	|j
krXt}
n|| }
||	j}|dk	r| ||
|	j|}|| q>|	jtjkr| |
}q>|	jtjkst|	j| |
}q>d}| j}|jr|d}|dk	r| |}tjtj||||jd||dS )zsGenerate schema for a Callable.

        TODO support functional validators once we support them in Config
        Zpositional_onlyZpositional_or_keywordkeyword_onlyNrz   )var_args_schemavar_kwargs_schemapopulate_by_name)r  )r   r=   Zget_function_type_hintsr	   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDKEYWORD_ONLYrP  r?  r  r  r   r   kindr  r  r   VAR_POSITIONALr   VAR_KEYWORDr8  r   Zvalidate_returnr"   r  r  r  )r   r  sigZ
type_hintsZmode_lookupZarguments_listr
  r  r  pr  Zparameter_modeZ
arg_schemar  r   Zreturn_hintr}   r}   r~   rw  A  sP    
   

zGenerateSchema._callable_schemaztyping.TypeVar)typevarrz   c                 C  s   t |tjst|j}|j}z| }W n$ tk
rL   t|dd d k	}Y nX |d k	t	|dk | dkrrt
d|r| |jS |r| tj| S |r| |}tjdd t d|d< |S t S d S )	N__default__r   r8   zZPydantic does not support mixing more than one of TypeVar bounds, constraints and defaultsc                 S  s   || S r   r}   )xhr}   r}   r~   r    r  z>GenerateSchema._unsubstituted_typevar_schema.<locals>.<lambda>r  r   )r   rt  r   r8  r  r  Zhas_defaultr  r   rO  NotImplementedErrorr   r  r  r   r"   r  r   )r   r  ro   constraintsZtypevar_has_defaultr   r}   r}   r~   rv  v  s.    
 
z,GenerateSchema._unsubstituted_typevar_schemazDecorator[ComputedFieldInfo]z2dict[str, Decorator[FieldSerializerDecoratorInfo]]zcore_schema.ComputedField)r-  r+  rz   c           	   
     s   zt  j jj| j}W n. tk
rH } zt||W 5 d }~X Y nX |t	kr^t
dddt|| j}tj j|d _| |}| j|t|  jdd}| jj}|d k	r| j| j jd dd	d
d fdd}t|gd}tj j| jj|dS )NzComputed field is missing return type annotation or specifying `return_type` to the `@computed_field` decorator (e.g. `@computed_field(return_type=int|str)`)zmodel-field-missing-annotationr   )return_typeTcomputed_fieldr  rB   r.   r5   )r   r   rz   c                   s   || }d|d<  j j}|d k	r(||d<  j j}|d k	r@||d<  j jsT j jdkr\d|d<  j j}|d k	rxt||d<  j j}|d k	rt|| |S )NTZreadOnlyr   r   r  r  r  )rx   r   r   r  r  r#   r  add_json_schema_extra)r   r   r   r   r   r  r  r-  r}   r~   set_computed_field_metadata  s"    
zJGenerateSchema._computed_field_schema.<locals>.set_computed_field_metadatar  )r  r  r  )r:   get_function_return_typefuncrx   r  r   rT  r3   rU  r!   r4   r^   r   r   replacer   r  r   r	  r   r   r  r  rA   r"   r  r  )	r   r-  r+  r  rW  Zreturn_type_schemar  r   r  r}   r  r~   r*    s@    
     z%GenerateSchema._computed_field_schema)annotated_typerz   c                 C  sL   ddl m} | j|dd^}}| ||}|D ]}t||r.t||}q.|S )zdGenerate schema for an Annotated type, e.g. `Annotated[int, Field(...)]` or `Annotated[int, Gt(0)]`.r+   r  Tr  )r|   rd   r;  r~  r   r  )r   r$  rd   r  r   r   r  r}   r}   r~   r_    s    

z GenerateSchema._annotated_schemaztuple[Any, list[Any]] | None)r   r   rz   c                 C  s^   ddl m} zt| W n tk
r.   Y d S X |D ]$}|||| jj}|d k	r4|  S q4d S )Nr8   )PREPARE_METHODS)ry  r%  hashr   r   rz  )r   r   r   r%  genr  r}   r}   r~   r}    s    
z?GenerateSchema._get_prepare_pydantic_annotations_for_known_typec                 C  s   | S r   r}   )r  r}   r}   r~   r    r  zGenerateSchema.<lambda>z	list[Any]z"Callable[[CoreSchema], CoreSchema])r  r   r  rz   c                   s   t t|} |t|}|dk	r.|\}}g }ddd fdd}t| }|D ]}|dkrdqV |||}qV||}	|rt|	j}
|
	dg 
| t jj||	S )a  Apply arguments from `Annotated` or from `FieldInfo` to a schema.

        This gets called by `GenerateSchema._annotated_schema` but differs from it in that it does
        not expect `source_type` to be an `Annotated` object, it expects it to be  the first argument of that
        (in other words, `GenerateSchema._annotated_schema` just unpacks `Annotated`, this process it).
        Nr   r    r   c                   s`     | | }|d kr  | }n|}t| |}|d k	rXt| jj}|d k	rX || |S r   )r  r  r  r  r   r  r  )r   r  r   r  r
  r   r  r}   r~   inner_handler  s    
z8GenerateSchema._apply_annotations.<locals>.inner_handler pydantic_js_annotation_functions)r  r<   Zexpand_grouped_metadatar}  r   r_   _get_wrapped_inner_schemar@   r  r  extendr   r   r   )r   r  r   r  r  r*  r)  get_inner_schemar  r   r  r}   r(  r~   r~    s(    
  
z!GenerateSchema._apply_annotations)r   r  rz   c           
      C  s`  ddl m} t||rJ|jD ]}| ||}q|jd k	rF| ||j}|S |d dkr|dt	 }| ||}|r~||d< |S |}|dd }|d k	r|
 }|dt|  }|| jjkr| jj| S ||d< nh|d dkr>|d	 }|| jjkr>| jj| 
 }|dt|  }|| jjkr6| jj| S ||d< t||
 }	|	d k	r\|	S |S )
Nr+   r  r   r   r   r   rR  definition-refr]  )r|   rd   r   r  _apply_single_annotationr   r   r   r"   r   r   reprr   r  r<   Zapply_known_metadata)
r   r   r  rd   field_metadatar   r   r   Znew_refZmaybe_updated_schemar}   r}   r~   r/  '  sB    




z'GenerateSchema._apply_single_annotationc                 C  s   ddl m} t||r|jD ]}| ||}qi }|jrB|j|d< |jrR|j|d< |jrft|j|d< |j	}|st|rt
|jdg t|| |S )Nr+   r  r   r   r  r*  )r|   rd   r   r  $_apply_single_annotation_json_schemar   r   r  r#   r  r@   r  r   r  )r   r   r  rd   r1  json_schema_updater  r}   r}   r~   r2  Q  s"    



z3GenerateSchema._apply_single_annotation_json_schemar-   zlist[GetJsonSchemaFunction]r_   )r-  r  r*  rz   c                   s:   t  dd pdd ddd fdd}t|S )	NrK  c                 S  s   || S r   r}   )rI  r   r}   r}   r~   r  o  r  z:GenerateSchema._get_wrapped_inner_schema.<locals>.<lambda>r   r   )rI  rz   c                   sB   | } | }| }t |}|d k	r>| |S r   )r/  r2  r  r   )rI  r   r  r  r-  Zmetadata_get_schemar*  r   r}   r~   new_handlerr  s    


z=GenerateSchema._get_wrapped_inner_schema.<locals>.new_handler)r   r_   )r   r-  r  r*  r5  r}   r4  r~   r+  h  s
    
z(GenerateSchema._get_wrapped_inner_schemaz-list[Decorator[FieldSerializerDecoratorInfo]])r   serializersr  rz   c              
   C  s@  |r<t |}|d dkr6|d }| |||d< |S td|dd}|dk	r\t|}|d }t|j|j	j
|d\}}zt|j|j	j| j}	W n. tk
r }
 zt|
|
W 5 d}
~
X Y nX |	tkrd}n
| |	}|j	j
d	krtj|j||||j	jd
|d< n0|j	j
dksttj|j||||j	jd
|d< |S )z$Apply field serializers to a schema.r   r  r   zstr|Noner   Nr   r  wrap)is_field_serializerr  r  r   r   plain)r   r  rt  r   r   r"   r  rT   r"  rx   r  r:   r!  r  r   rT  r3   rU  r!   r   r  r   r8  r   )r   r   r6  r  r   r   
serializerr8  r  r  rW  r  r}   r}   r~   r  ~  sV    
  
  

z'GenerateSchema._apply_field_serializersz1Iterable[Decorator[ModelSerializerDecoratorInfo]])r   r6  rz   c           
   
   C  s   | dd}|rt|d }t|j|jj}zt|j|jj| j	}W n. t
k
rt } zt||W 5 d}~X Y nX |tkrd}n
| |}|jjdkrtj|j|||jjd}	ntj|j|||jjd}	|	|d< |r||d< |S )z$Apply model serializers to a schema.r   Nr   r7  )r  r  r   r   )r   r  rU   r"  rx   r  r:   r!  r  r   rT  r3   rU  r!   r   r"   r  r   r   )
r   r   r6  r   r:  r  r  rW  r  Z
ser_schemar}   r}   r~   rA    s@      
z'GenerateSchema._apply_model_serializers)N)T)F)F)Ir   r   r   r   r  r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   	Exceptionr  r  r  r  r   rD  rH  r  rX  r   r;  rZ  r\  r  r`  r  r  r#  r  staticmethodr  r  r<  r  rg  ri  rj  rl  r	   r  r  rf  rh  r  r  r  r  rp  ru  r|  rw  rv  r*  r_  r}  r~  r/  r2  r+  r  rA  r}   r}   r}   r~   r   3  s    
	 /`;	V21*gj(#c5A/* 7r   c                 C  s   t | |S r   )r"   !no_info_before_validator_functionfr   rR  r}   r}   r~   r    r  r  c                 C  s   t | |S r   )r"    no_info_after_validator_functionr?  r}   r}   r~   r    r  c                 C  s
   t | S r   )r"   r  )r@  r  r  r}   r}   r~   r    r  c                 C  s   t | |S r   )r"   r  r?  r}   r}   r~   r    r  c                 C  s   t j| ||dS N)r   )r"   #with_info_before_validator_functionr@  r   r   r}   r}   r~   r    s     c                 C  s   t j| ||dS rB  )r"   "with_info_after_validator_functionrD  r}   r}   r~   r    s     c                 C  s   t j| |dS rB  rM  )r@  rR  r   r}   r}   r~   r    s    c                 C  s   t j| ||dS rB  )r"   !with_info_wrap_validator_functionrD  r}   r}   r~   r    s     ))beforeno-info)afterrH  )r9  rH  )r7  rH  )rG  	with-info)rI  rJ  )r9  rJ  )r7  rJ  zMapping[tuple[FieldValidatorModes, Literal[('no-info', 'with-info')]], Callable[[Callable[..., Any], core_schema.CoreSchema, str | None], core_schema.CoreSchema]]_VALIDATOR_F_MATCHzIterable[Decorator[RootValidatorDecoratorInfo]] | Iterable[Decorator[ValidatorDecoratorInfo]] | Iterable[Decorator[FieldValidatorDecoratorInfo]])r   r4  r   rz   c                 C  sD   |D ]:}t |j|jj}|r dnd}t|jj|f |j| |} q| S )a  Apply validators to a schema.

    Args:
        schema: The schema to apply validators on.
        validators: An iterable of validators.
        field_name: The name of the field if validators are being applied to a model field.

    Returns:
        The updated schema.
    rJ  rH  )rV   r"  rx   r  rK  )r   r4  r   	validatorr  Zval_typer}   r}   r~   r     s
    r   z+Iterable[Decorator[ValidatorDecoratorInfo]])r4  rz   c                 C  s   | D ]}|j jr dS qdS )a?  In v1, if any of the validators for a field had `always=True`, the default value would be validated.

    This serves as an auxiliary function for re-implementing that logic, by looping over a provided
    collection of (v1-style) ValidatorDecoratorInfo's and checking if any of them have `always=True`.

    We should be able to drop this function and the associated logic calling it once we drop support
    for v1-style validator decorators. (Or we can extend it and keep it if we add something equivalent
    to the v1-validator `always` kwarg to `field_validator`.)
    TF)rx   always)r4  rL  r}   r}   r~   r    s    
r  z0Iterable[Decorator[ModelValidatorDecoratorInfo]]z"Literal[('inner', 'outer', 'all')])r   r4  r  rz   c                 C  s   |  dd}|D ]}|dkr*|jjdkr*q|dkr@|jjdkr@qt|j|jj}|jjdkr|rrtj|j| d} qtj|j| d} q|jjdkr|rtj|j| d} qtj	|j| d} q|jjdkst
|rtj|j| d} qtj|j| d} q|r|| d< | S )	a  Apply model validators to a schema.

    If mode == 'inner', only "before" validators are applied
    If mode == 'outer', validators other than "before" are applied
    If mode == 'all', all validators are applied

    Args:
        schema: The schema to apply validators on.
        validators: An iterable of validators.
        mode: The validator mode.

    Returns:
        The updated schema.
    r   Nr   rG  r0  r7  )r  r   rI  )r   rx   r  rV   r"  r"   rF  r  rC  r>  r8  rE  rA  )r   r4  r  r   rL  r  r}   r}   r~   r=    s,    r=  rd   )r  r   rz   c                 C  s@   | j rtj|| j | jdS | jtk	r8tj|| j| jdS |S dS )a  Wrap schema with default schema if default value or `default_factory` are available.

    Args:
        field_info: The field info object.
        schema: The schema to apply default on.

    Returns:
        Updated schema by default value or `default_factory`.
    )default_factoryr  )r  r  N)rN  r"   Zwith_default_schemar  r  r!   )r  r   r}   r}   r~   r  M  s    
  
  r  zGetJsonSchemaFunction | None)r   r   rz   c                 C  s   t | dd}t| drvddlm} |dk	o@|jj|t |ddfk}|svt | dd}td|rfd	| d
nd dddt| drt| tt	t
df st| j|S |dkrdS |S )z`Extract `__get_pydantic_json_schema__` from a type, handling the deprecated `__modify_schema__`.__get_pydantic_json_schema__NZ__modify_schema__r   re   __func__r   zjThe `__modify_schema__` method is not supported in Pydantic v2. Use `__get_pydantic_json_schema__` insteadz in class ``r  r   zcustom-json-schemar   
__origin__placeholder)r   r  Zpydanticrf   rO  rP  r4   r   r   r$   rc  r  rR  )r   r   Zjs_modify_functionrf   Zhas_custom_v2_modify_js_funccls_namer}   r}   r~   r  c  s&    
 r  z3JsonDict | typing.Callable[[JsonDict], None] | Nonerj   )r3  r  rz   c                   s   dddd fdd}|S )NrB   r.   r5   )core_schema_or_fieldr   rz   c                   s   || }t |  |S r   )r  )rU  r   r   r  r3  r}   r~   json_schema_update_func  s    
z<get_json_schema_update_func.<locals>.json_schema_update_funcr}   )r3  r  rW  r}   rV  r~   r    s    r  r   r  c                 C  s.   t |tr| t| nt|r*||  d S r   )r   r   rG  r#   callablerX  r}   r}   r~   r    s    
r  c                   @  s>   e Zd ZU ded< ded< ded< ded< ded	< d
ed< dS )r  r   r   4str | list[str | int] | list[list[str | int]] | Noner  r   r  bool | Noner  r  zdict[str, Any]r  N)r   r   r   r  r}   r}   r}   r~   r    s   
r  )r  r  r  r  r  rZ  r[  )r   r  r  r  r  r  rz   c                C  s   | |||||dS )Nr   r  r  r  r  r  r}   r\  r}   r}   r~   r    s    
r  c                   @  s2   e Zd ZdZddddZedddd	d
ZdS )r   z*Keeps track of references and definitions.r   r   c                 C  s   t  | _i | _d S r   )r   seenr  r   r}   r}   r~   r     s    z_Definitions.__init__r   z3Iterator[tuple[str, None] | tuple[str, CoreSchema]]r   c              	   c  s\   t |}|| jks|| jkr.|t|fV  n*| j| z|dfV  W 5 | j| X dS )ao  Get a definition for `tp` if one exists.

        If a definition exists, a tuple of `(ref_string, CoreSchema)` is returned.
        If no definition exists yet, a tuple of `(ref_string, None)` is returned.

        Note that the returned `CoreSchema` will always be a `DefinitionReferenceSchema`,
        not the actual definition itself.

        This should be called for any type that can be identified by reference.
        This includes any recursive types.

        At present the following types can be named/recursive:

        - BaseModel
        - Dataclasses
        - TypedDict
        - TypeAliasType
        N)rF   r]  r  r"   r  adddiscard)r   r   r   r}   r}   r~   r1    s    z_Definitions.get_schema_or_refN)r   r   r   r   r   r   r1  r}   r}   r}   r~   r     s   r   zdict[str, CoreSchema]zCoreSchema | None)r   r  rz   c                 C  s8   | d dkr| | d d S | d dkr0| d S | S d S )Nr   r.  r]  r  r   r  )r   r  r}   r}   r~   r    s
    r  c                   @  s@   e Zd ZdZddddZedddd	d
ZddddZdS )r   _stackr   r   c                 C  s
   g | _ d S r   r`  r   r}   r}   r~   r     s    z_FieldNameStack.__init__rv   Iterator[None])r   rz   c                 c  s    | j | d V  | j   d S r   ra  r   r   )r   r   r}   r}   r~   r     s    z_FieldNameStack.pushr   c                 C  s   | j r| j d S d S d S r   r`  r   r}   r}   r~   r     s    
z_FieldNameStack.getNr   r   r   r  r   r   r   r   r}   r}   r}   r~   r     s
   r   c                   @  s@   e Zd ZdZddddZedddd	d
ZddddZdS )r   r`  r   r   c                 C  s
   g | _ d S r   r`  r   r}   r}   r~   r     s    z_ModelTypeStack.__init__r   rb  )type_objrz   c                 c  s    | j | d V  | j   d S r   rc  )r   re  r}   r}   r~   r     s    z_ModelTypeStack.pushztype | Nonec                 C  s   | j r| j d S d S d S r   r`  r   r}   r}   r~   r   	  s    
z_ModelTypeStack.getNrd  r}   r}   r}   r~   r     s
   r   )r   
__future__r   Z_annotationscollections.abcrq  r   r   rn  sysrt  r   
contextlibr   r   r   r   enumr   	functoolsr   r	   r
   r   	itertoolsr   operatorr   typesr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zpydantic_corer    r!   r"   r#   Ztyping_extensionsr$   r%   r&   r'   r(   r)   r*   aliasesr,   Zannotated_handlersr-   r.   r"  r/   r0   r1   errorsr2   r3   r4   r   r5   versionr6   r7   r  r9   r:   r;   r<   r=   _configr>   r?   Z_core_metadatar@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   Z_docs_extractionrW   r  rX   rY   Z_forward_refrZ   Z	_genericsr[   r\   r]   r^   Z_schema_generation_sharedr_   r`   ra   _utilsrb   r|   rc   rd   r   rf   rg   r4  rh   Z_dataclassesri   rj   version_infor  r   rc  r^  ru   rn   ZAnyFieldDecoratorZModifyCoreSchemaWrapHandlerZGetCoreSchemaFunctionr   Tuplerp   r  r  Listrr  MutableSequencerq   r   Set
MutableSetrr   	frozenset	FrozenSetrs   r   MutableMappingrt   r   r   r   r   r   ZJsonEncodersr   rv   r   r   r   r   rK  r   r  r=  r  r  r  r  r  r  r   r  r   r   r}   r}   r}   r~   <module>   s   @$,8
%""	             <
/	'	