
    g4                        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m	Z	m
Z
mZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZ dd
lmZmZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ejN                  rdZ(de)d<   dZ*de)d<   ddl+m,Z, e-e.e/e0e1e2e3e$jh                  eeeejj                  eee6jn                  e8jn                  hZ9de)d<   e:e;e<e=e>e	e
ehZ?de)d<   d1dZ@d2dZAd3dZBd4dZCd5dZDd6dZE ed      ZFd7d ZGd8d!ZH ed"      ZIe0d#	 	 	 	 	 d9d$ZJ G d% d&e#j                        ZLejN                  rd:d'ZMn
 G d( d)      ZM ed*      ZNd;d+ZO eP       ZQd<d,ZR ej                  d-.       G d/ d0             ZTy)=zBucket of reusable internal utilities.

This should be reduced as much as possible with functions only used in one place, moved to that place.
    )annotationsN)OrderedDictdefaultdictdeque)deepcopy)cached_property)	Parameter)zip_longest)BuiltinFunctionTypeCodeTypeFunctionTypeGeneratorType
LambdaType
ModuleType)AnyCallableMappingTypeVar)	TypeAlias	TypeGuard   )_repr_typing_extra)import_cached_base_modelz3typing.Mapping[int, Any] | typing.Mapping[str, Any]r   MappingIntStrAnyz1typing.AbstractSet[int] | typing.AbstractSet[str]AbstractSetIntStr   )	BaseModelzset[type[Any]]IMMUTABLE_NON_COLLECTIONS_TYPESBUILTIN_COLLECTIONSc                Z    | j                   t        j                  t        j                  fv S )aZ  Return whether the parameter accepts a positional argument.

    ```python {test="skip" lint="skip"}
    def func(a, /, b, *, c):
        pass

    params = inspect.signature(func).parameters
    can_be_positional(params['a'])
    #> True
    can_be_positional(params['b'])
    #> True
    can_be_positional(params['c'])
    #> False
    ```
    )kindr	   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORD)params    N/var/www/openai/venv/lib/python3.12/site-packages/pydantic/_internal/_utils.pycan_be_positionalr'   C   s$      ::)33Y5T5TUUU    c           	     V    t        | t        t        t        t        t
        t        f      S N)
isinstancelisttupleset	frozensetr   r   vs    r&   sequence_liker2   V   s    a$sI}eLMMr(   c                :    	 t        | |      S # t        $ r Y yw xY wNF)r+   	TypeError)oclass_or_tuples     r&   lenient_isinstancer8   Z   s&    !^,, s    	c                    	 t        | t              xr t        | |      S # t        $ r t        | t        j
                        rY y w xY wr4   )r+   type
issubclassr5   r   WithArgsTypes)clsr7   s     r&   lenient_issubclassr>   a   sE    #t$HC)HH c=667s     #AAc                :    t               }t        | |      xr | |uS )zReturns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
    unlike raw calls to lenient_issubclass.
    )r   r>   )r=   r   s     r&   is_model_classr@   j   s#     )*Ic9-F#Y2FFr(   c                R    | j                         xr t        j                  |        S )zChecks that a string is a valid identifier and not a Python keyword.
    :param identifier: The identifier to test.
    :return: True if the identifier is valid.
    )isidentifierkeyword	iskeyword)
identifiers    r&   is_valid_identifierrF   s   s&    
 ""$JW->->z-J)JJr(   KeyTypec                    | j                         }|D ]Y  }|j                         D ]D  \  }}||v r6t        ||   t              r#t        |t              rt	        ||   |      ||<   @|||<   F [ |S r*   )copyitemsr+   dictdeep_update)mappingupdating_mappingsupdated_mappingupdating_mappingkr1   s         r&   rL   rL   ~   sy    llnO-$**,DAqO#
?13Et(LQ[\]_cQd%01CQ%G"%&"	 - . r(   c                |    | j                  |j                         D ci c]  \  }}|	|| c}}       y c c}}w r*   )updaterJ   )rM   rS   rQ   r1   s       r&   update_not_nonerT      s2    NNV\\^E^TQq}AqD^EFEs   
8
8
T)name_factoryc                   g }g }| D ]E  } ||      }||vr#|j                  |       |j                  |       2|||j                  |      <   G |S )zMake a list unique while maintaining order.
    We update the list if another one with the same name is set
    (e.g. model validator overridden in subclass).
    )appendindex)
input_listrV   resultresult_namesr1   v_names         r&   unique_listr^      s_     F La%'MM!12F<%%f-.  Mr(   c                      e Zd ZdZdZddZddZddZddZddZ	e
ddd       Zedd	       Ze
dd
       Zedd       ZddZy)
ValueItemszOClass for more convenient calculation of excluded or included fields on values.)_items_typec                    | j                  |      }t        |t        t        f      r| j	                  |t        |            }|| _        y r*   )_coerce_itemsr+   r,   r-   _normalize_indexeslenra   )selfvaluerJ   s      r&   __init__zValueItems.__init__   s=    ""5)edE]+++E3u:>E(-r(   c                V    | j                  | j                  j                  |            S )zWCheck if item is fully excluded.

        :param item: key or index of a value
        )is_truera   getrg   items     r&   is_excludedzValueItems.is_excluded   s     
 ||DKKOOD122r(   c                    || j                   v S )z`Check if value is contained in self._items.

        :param item: key or index of value
        ra   rm   s     r&   is_includedzValueItems.is_included   s    
 t{{""r(   c                b    | j                   j                  |      }| j                  |      s|S dS )z:param e: key or index of element on value
        :return: raw values for element if self._items is dict and contain needed element
        N)ra   rl   rk   )rg   ern   s      r&   for_elementzValueItems.for_element   s,     {{q!<<-t747r(   c                   i }d}|j                         D ]  \  }}t        |t        j                        sFt        |t        j                        s,| j                  |      st        d| d|j                         |dk(  r| j                  |      }}t        |t              st        d      |dk  r||z   n|}| j                  ||j                  |            ||<    |s|S | j                  |      r$t        |      D ]  }|j                  |d        |S t        |      D ];  }|j                  |i       }| j                  |      r'| j                  ||      ||<   = |S )a]  :param items: dict or set of indexes which will be normalized
        :param v_length: length of sequence indexes of which will be

        >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
        {0: True, 2: True, 3: True}
        >>> self._normalize_indexes({'__all__': True}, 4)
        {0: True, 1: True, 2: True, 3: True}
        Nz,Unexpected type of exclude value for index "z" __all__zExcluding fields from a sequence of sub-models or dicts must be performed index-wise: expected integer keys or keyword "__all__"r   .)rJ   r+   typingr   AbstractSetrk   r5   	__class___coerce_valueintmergerl   range
setdefault)	rg   rJ   v_lengthnormalized_items	all_itemsir1   normalized_inormalized_items	            r&   re   zValueItems._normalize_indexes   sc    24	KKMDAqq&..1Z6CUCU5VZ^ZfZfghZi"NqcQSTUT_T_S` abbI~ ..q1	a%A  ,-q58a<aL-1ZZ;K;O;OP\;]-^\* " ##<<	"8_ ++As3 %##xA.99!R@O<<0&*jjO&L # !  r(   c                   | j                  |      }| j                  |      }||S | j                  |      s||S | j                  |      r|r|S |S |r,|D cg c]	  }||v s| c}|D cg c]	  }||v s| c}z   }n!t        |      |D cg c]	  }||vs| c}z   }i }|D ]<  }| j                  |j	                  |      |j	                  |      |      }|8|||<   > |S c c}w c c}w c c}w )aH  Merge a `base` item with an `override` item.

        Both `base` and `override` are converted to dictionaries if possible.
        Sets are converted to dictionaries with the sets entries as keys and
        Ellipsis as values.

        Each key-value pair existing in `base` is merged with `override`,
        while the rest of the key-value pairs are updated recursively with this function.

        Merging takes place based on the "union" of keys if `intersect` is
        set to `False` (default) and on the intersection of keys if
        `intersect` is set to `True`.
        )	intersect)r{   rk   r,   r}   rl   )r=   baseoverrider   rQ   
merge_keysmergedmerged_items           r&   r}   zValueItems.merge   s    $$X.  &K;;tO;;x $42(2 %);TQ(]!T;(>`(QVW[_V_q(>``Jd(&L(Qatmq(&LLJ')A))DHHQKaI)VK&'q	 
  <>`&Ls$   	C'#C'-	C,7C,	C1C1c                    t        | t        j                        r	 | S t        | t        j                        rt        j                  | d      } | S t        | dd      }t        d|       )N.rz   z???z!Unexpected type of exclude value )r+   rx   r   ry   rK   fromkeysgetattrr5   )rJ   
class_names     r&   rd   zValueItems._coerce_items  sf    eV^^,  v112MM%-E  !U;J?
|LMMr(   c                N    || j                  |      r|S | j                  |      S r*   )rk   rd   )r=   rh   s     r&   r{   zValueItems._coerce_value  s(    =CKK.L  ''r(   c                    | du xs | du S )NT. r0   s    r&   rk   zValueItems.is_true$  s    Dy$AH$r(   c                     d | j                   fgS r*   rq   rg   s    r&   __repr_args__zValueItems.__repr_args__(  s    t{{#$$r(   N)rh   r   rJ   $AbstractSetIntStr | MappingIntStrAnyreturnNone)rn   r   r   bool)rt   z	int | strr   z+AbstractSetIntStr | MappingIntStrAny | None)rJ   r   r   r|   r   zdict[int | str, Any])F)r   r   r   r   r   r   r   r   )rJ   r   r   r   )rh   r   r   r   r1   r   r   r   )r   z_repr.ReprArgs)__name__
__module____qualname____doc__	__slots__ri   ro   rr   ru   re   classmethodr}   staticmethodrd   r{   rk   r   r   r(   r&   r`   r`      sz    Y#I.3#8# J # #J   ( (
 % %%r(   r`   c                     y r*   r   name	get_values     r&   LazyClassAttributer   .  s    r(   c                  2    e Zd ZdZddZedd       ZddZy)	r   zA descriptor exposing an attribute only accessible on a class (hidden from instances).

        The attribute is lazily computed and cached during the first access.
        c                     || _         || _        y r*   r   )rg   r   r   s      r&   ri   zLazyClassAttribute.__init__8  s    DI&DNr(   c                "    | j                         S r*   )r   r   s    r&   rh   zLazyClassAttribute.value<  s    >>##r(   c                h    || j                   S t        | j                  d|j                  d      )Nz attribute of z is class-only)rh   AttributeErrorr   r   )rg   instanceowners      r&   __get__zLazyClassAttribute.__get__@  s4    zz! DII=u~~>PP^!_``r(   N)r   strr   zCallable[[], Any]r   r   )r   r   )r   r   r   z	type[Any]r   r   )r   r   r   r   ri   r   rh   r   r   r(   r&   r   r   2  s&    	
	' 
	$ 
	$	ar(   r   Objc                    | j                   }|t        v r| S 	 | s"|t        v r|t        u r| S | j	                         S t        |       S # t
        t        t        f$ r Y t        |       S w xY w)zReturn type as is for immutable built-in types
    Use obj.copy() for built-in empty collections
    Use copy.deepcopy() for non-empty collections and unknown objects.
    )	rz   r   r    r-   rI   r5   
ValueErrorRuntimeErrorr   )objobj_types     r&   smart_deepcopyr   I  st    
 }}H22
x#66"e+3;;
 C=	 z<0 C=	s   A A A('A(c                D    t        | |t              D ]  \  }}||us y y)a  Check that the items of `left` are the same objects as those in `right`.

    >>> a, b = object(), object()
    >>> all_identical([a, b, a], [a, b, a])
    True
    >>> all_identical([a, b, [a]], [a, b, [a]])  # new list object, while "equal" is not "identical"
    False
    )	fillvalueFT)r
   	_SENTINEL)leftright	left_item
right_items       r&   all_identicalr   _  s-     "-T5I!N	:J& "O r(   T)frozenc                  J    e Zd ZU dZdZded<   ddZej                  rd	dZ	yy)
SafeGetItemProxyzWrapper redirecting `__getitem__` to `get` with a sentinel value as default

    This makes is safe to use in `operator.itemgetter` when some keys may be missing
    )wrappedzMapping[str, Any]r   c               B    | j                   j                  |t              S r*   )r   rl   r   rg   keys     r&   __getitem__zSafeGetItemProxy.__getitem__{  s    ||Y//r(   c               8    | j                   j                  |      S r*   )r   __contains__r   s     r&   r   zSafeGetItemProxy.__contains__  s    <<,,S11r(   N)r   r   r   r   )r   r   r   r   )
r   r   r   r   r   __annotations__r   rx   TYPE_CHECKINGr   r   r(   r&   r   r   n  s.     I0 	2 r(   r   )r%   r	   r   r   r   )r6   r   r7   z(type[Any] | tuple[type[Any], ...] | Noner   r   )r=   r   r7   r   r   r   )r=   r   r   zTypeGuard[type[BaseModel]])rE   r   r   r   )rM   dict[KeyType, Any]rN   r   r   r   )rM   zdict[Any, Any]rS   r   r   r   )rZ   zlist[T] | tuple[T, ...]rV   ztyping.Callable[[T], str]r   zlist[T])r   r   r   zCallable[[], T]r   rU   )r   r   r   r   )r   typing.Iterable[Any]r   r   r   r   )Ur   
__future__r   _annotationsdataclassesrC   rx   weakrefcollectionsr   r   r   rI   r   	functoolsr   inspectr	   	itertoolsr
   typesr   r   r   r   r   r   r   r   r   r   typing_extensionsr   r    r   r   _import_utilsr   r   r   r   r   mainr   r|   floatcomplexr   r   bytesr:   NoneTyperefNotImplementedrz   Ellipsisr   r,   r.   r-   r/   rK   r    r'   r2   r8   r>   r@   rF   rG   rL   rT   rU   r^   Representationr`   r   r   r   objectr   r   	dataclassr   r   r(   r&   <module>r      s  
 3     7 7  %  ! d d 2 2 2 " 3	"WiW#VyV 
 		KK '3  0 				' ^ 	V&NGK )
G CL /2' , 	,C%%% C%L 
Ka a( en& H	 d#2 2 $2r(   