o
    h`                     @  s  U d dl m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
 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 d dlmZ d d	lmZmZmZmZ d d
lm Z  d dl!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* er}d dl+m,Z, eee-eeee-f  eeee-f df f Z.edZ/de0d< G dd de1Z2G dd deZ3G dd de3Z4G dd de3Z5G dd de5Z6G dd de5Z7G d d! d!e7Z8dd"d#d6d,d-Z9d7d2d3Z:d8d4d5Z;dS )9    )annotationsN)ABCabstractmethod)deque)is_dataclass)Path)TYPE_CHECKINGAnyListMappingSequenceTupleUnioncast)dotenv_values)AliasChoices	AliasPath	BaseModelJson)origin_is_union)deep_updatelenient_issubclass)	FieldInfo)get_args
get_origin)path_type_label)BaseSettings. 
DotenvTypeENV_FILE_SENTINELc                   @  s   e Zd ZdS )SettingsErrorN)__name__
__module____qualname__ r$   r$   O/var/www/html/ai/venv/lib/python3.10/site-packages/pydantic_settings/sources.pyr    !   s    r    c                   @  sT   e Zd ZdZdddZedddZdddZdddZd ddZ	ed!ddZ
dS )"PydanticBaseSettingsSourcezi
    Abstract base class for settings sources, every settings source classes should inherit from it.
    settings_clstype[BaseSettings]c                 C  s   || _ |j| _d S N)r'   model_configconfig)selfr'   r$   r$   r%   __init__*   s   z#PydanticBaseSettingsSource.__init__fieldr   
field_namestrreturntuple[Any, str, bool]c                 C     dS )a  
        Gets the value, the key for model creation, and a flag to determine whether value is complex.

        This is an abstract method that should be overridden in every settings source classes.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value and a flag to determine whether value is complex.
        Nr$   r,   r.   r/   r$   r$   r%   get_field_value.   s   z*PydanticBaseSettingsSource.get_field_valueboolc                 C  s   t |j|jS )z
        Checks whether a field is complex, in which case it will attempt to be parsed as JSON.

        Args:
            field: The field.

        Returns:
            Whether the field is complex.
        )_annotation_is_complex
annotationmetadata)r,   r.   r$   r$   r%   field_is_complex>   s   
z+PydanticBaseSettingsSource.field_is_complexvaluer	   value_is_complexc                 C  s(   |dur|  |s|r| |||S |S )aF  
        Prepares the value of a field.

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.
            value_is_complex: A flag to determine whether value is complex.

        Returns:
            The prepared value.
        N)r:   decode_complex_value)r,   r/   r.   r;   r<   r$   r$   r%   prepare_field_valueJ   s   z.PydanticBaseSettingsSource.prepare_field_valuec                 C  s
   t |S )a  
        Decode the value for a complex field

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.

        Returns:
            The decoded value for further preparation
        )jsonloads)r,   r/   r.   r;   r$   r$   r%   r=   [   s   
z/PydanticBaseSettingsSource.decode_complex_valuedict[str, Any]c                 C  s   d S r)   r$   r,   r$   r$   r%   __call__i      z#PydanticBaseSettingsSource.__call__N)r'   r(   r.   r   r/   r0   r1   r2   )r.   r   r1   r6   
r/   r0   r.   r   r;   r	   r<   r6   r1   r	   )r/   r0   r.   r   r;   r	   r1   r	   r1   rA   )r!   r"   r#   __doc__r-   r   r5   r:   r>   r=   rC   r$   r$   r$   r%   r&   %   s    



r&   c                      s@   e Zd ZdZd fddZdddZdddZdddZ  ZS )InitSettingsSourcezX
    Source class for loading values provided during settings class initialization.
    r'   r(   init_kwargsrA   c                   s   || _ t | d S r)   )rJ   superr-   )r,   r'   rJ   	__class__r$   r%   r-   s   s   zInitSettingsSource.__init__r.   r   r/   r0   r1   r2   c                 C  r3   )N)Nr   Fr$   r4   r$   r$   r%   r5   w   rD   z"InitSettingsSource.get_field_valuec                 C  s   | j S r)   rJ   rB   r$   r$   r%   rC   {   s   zInitSettingsSource.__call__c                 C     d| j dS )NzInitSettingsSource(init_kwargs=)rN   rB   r$   r$   r%   __repr__~      zInitSettingsSource.__repr__)r'   r(   rJ   rA   rE   rG   r1   r0   )	r!   r"   r#   rH   r-   r5   rC   rQ   __classcell__r$   r$   rL   r%   rI   n   s    

rI   c                      sJ   e Zd Z	dd fd
dZdddZdddZd ddZd!ddZ  ZS )"PydanticBaseEnvSettingsSourceNr'   r(   case_sensitivebool | None
env_prefix
str | Noner1   Nonec                   sN   t  | |d ur|n| jdd| _|d ur|| _d S | jdd| _d S )NrV   FrX   r   )rK   r-   r+   getrV   rX   )r,   r'   rV   rX   rL   r$   r%   r-      s   &z&PydanticBaseEnvSettingsSource.__init__r;   r0   c                 C  s   | j s| S |S r)   )rV   lower)r,   r;   r$   r$   r%   _apply_case_sensitive   s   z3PydanticBaseEnvSettingsSource._apply_case_sensitiver.   r   r/   list[tuple[str, str, bool]]c                 C  s   g }t |jttfr|j }n|j}|rft |trY|D ]:}t |tr7||| |t	|dkr2dndf qt |trVt
t|d }||| |t	|dkrRdndf q|S ||| |df |S ||| | j| df |S )a  
        Extracts field info. This info is used to get the value of field from environment variables.

        It returns a list of tuples, each tuple contains:
            * field_key: The key of field that has to be used in model creation.
            * env_name: The environment variable name of the field.
            * value_is_complex: A flag to determine whether the value from environment variable
              is complex and has to be parsed.

        Args:
            field (FieldInfo): The field.
            field_name (str): The field name.

        Returns:
            list[tuple[str, str, bool]]: List of tuples, each tuple contains field_key, env_name, and value_is_complex.
           TFr   )
isinstancevalidation_aliasr   r   convert_to_aliaseslistr0   appendr]   lenr   rX   )r,   r.   r/   
field_infov_aliasalias	first_argr$   r$   r%   _extract_field_info   s(   

(
z1PydanticBaseEnvSettingsSource._extract_field_infofield_valuesrA   c           	      C  s   i }|  D ]M\}}d}|jrt|jds|||< q|jj  D ]\}}|js3| | kr3|} nq |s;|||< qt|jtrOt|t	rO| 
||||< q|||< q|S )ae  
        Replace field names in values dict by looking in models fields insensitively.

        By having the following models:

            ```py
            class SubSubSub(BaseModel):
                VaL3: str

            class SubSub(BaseModel):
                Val2: str
                SUB_sub_SuB: SubSubSub

            class Sub(BaseModel):
                VAL1: str
                SUB_sub: SubSub

            class Settings(BaseSettings):
                nested: Sub

                model_config = SettingsConfigDict(env_nested_delimiter='__')
            ```

        Then:
            _replace_field_names_case_insensitively(
                field,
                {"val1": "v1", "sub_SUB": {"VAL2": "v2", "sub_SUB_sUb": {"vAl3": "v3"}}}
            )
            Returns {'VAL1': 'v1', 'SUB_sub': {'Val2': 'v2', 'SUB_sub_SuB': {'VaL3': 'v3'}}}
        Nmodel_fields)itemsr8   hasattrrl   ra   r\   r   r   r`   dict'_replace_field_names_case_insensitively)	r,   r.   rk   valuesnamer;   sub_model_fieldsub_model_field_namefr$   r$   r%   rp      s$   
zEPydanticBaseEnvSettingsSource._replace_field_names_case_insensitivelyc                 C  s   i }| j j D ]n\}}z| ||\}}}W n ty1 } ztd| d| jj d|d }~ww z
| ||||}W n t	yV } ztd| d| jj d|d }~ww |d urv| j
srt|jtrrt|trr| ||||< q|||< q|S )Nzerror getting value for field "z" from source ""zerror parsing value for field ")r'   rl   rm   r5   	Exceptionr    rM   r!   r>   
ValueErrorrV   r   r8   r   r`   ro   rp   )r,   datar/   r.   field_value	field_keyr<   er$   r$   r%   rC      sB   
z&PydanticBaseEnvSettingsSource.__call__)NN)r'   r(   rV   rW   rX   rY   r1   rZ   )r;   r0   r1   r0   )r.   r   r/   r0   r1   r^   )r.   r   rk   rA   r1   rA   rG   )	r!   r"   r#   r-   r]   rj   rp   rC   rT   r$   r$   rL   r%   rU      s    


(;rU   c                      sZ   e Zd ZdZ			d"d# fddZd$ fddZed%ddZd&ddZd'd d!Z	  Z
S )(SecretsSettingsSourcezE
    Source class for loading settings values from secret files.
    Nr'   r(   secrets_dirstr | Path | NonerV   rW   rX   rY   r1   rZ   c                   s4   t  ||| |d ur|| _d S | jd| _d S )Nr~   )rK   r-   r+   r[   r~   )r,   r'   r~   rV   rX   rL   r$   r%   r-     s   $zSecretsSettingsSource.__init__rA   c                   sl   i }| j du r	|S t| j  | _| j s"td| j d |S | j s1tdt	| j t
  S )z4
        Build fields from "secrets" files.
        Nzdirectory "z" does not existz.secrets_dir must reference a directory, not a )r~   r   
expandusersecrets_pathexistswarningswarnis_dirr    r   rK   rC   )r,   secretsrL   r$   r%   rC     s   



zSecretsSettingsSource.__call__dir_pathr   	file_namer0   r6   Path | Nonec                 C  sB   |  D ]}|j|kr|  S |s|j | kr|  S qdS )af  
        Find a file within path's directory matching filename, optionally ignoring case.

        Args:
            dir_path: Directory path.
            file_name: File name.
            case_sensitive: Whether to search for file name case sensitively.

        Returns:
            Whether file path or `None` if file does not exist in directory.
        N)iterdirrr   r\   )clsr   r   rV   ru   r$   r$   r%   find_case_path2  s   
z$SecretsSettingsSource.find_case_pathr.   r   r/   r2   c                 C  sx   |  ||D ]0\}}}| | j|| j}|sq| r&|  ||f  S tjd| dt	| ddd qd||fS )ag  
        Gets the value for field from secret file and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value if the file exists otherwise `None`, and
                a flag to determine whether value is complex.
        zattempted to load secret file "z" but found a z	 instead.   )
stacklevelN)
rj   r   r   rV   is_file	read_textstripr   r   r   )r,   r.   r/   r{   env_namer<   pathr$   r$   r%   r5   F  s   
z%SecretsSettingsSource.get_field_valuec                 C  rO   )Nz"SecretsSettingsSource(secrets_dir=rP   )r~   rB   r$   r$   r%   rQ   c  rR   zSecretsSettingsSource.__repr__NNN)
r'   r(   r~   r   rV   rW   rX   rY   r1   rZ   rG   )r   r   r   r0   rV   r6   r1   r   rE   rS   )r!   r"   r#   rH   r-   rC   classmethodr   r5   rQ   rT   r$   r$   rL   r%   r}     s    

r}   c                      s~   e Zd ZdZ			d1d2 fddZd3ddZd4ddZd5ddZd6d"d#Zd7d%d&Z	e
d8d)d*Zd9d-d.Zd:d/d0Z  ZS );EnvSettingsSourcezN
    Source class for loading settings values from environment variables.
    Nr'   r(   rV   rW   rX   rY   env_nested_delimiterr1   rZ   c                   sD   t  ||| |d ur|n| jd| _t| j| _|  | _	d S )Nr   )
rK   r-   r+   r[   r   re   rX   env_prefix_len_load_env_varsenv_vars)r,   r'   rV   rX   r   rL   r$   r%   r-   l  s
   zEnvSettingsSource.__init__Mapping[str, str | None]c                 C  s    | j rtjS dd tj D S )Nc                 S     i | ]	\}}|  |qS r$   r\   .0kvr$   r$   r%   
<dictcomp>~      z4EnvSettingsSource._load_env_vars.<locals>.<dictcomp>)rV   osenvironrm   rB   r$   r$   r%   r   {  s   z EnvSettingsSource._load_env_varsr.   r   r/   r0   r2   c                 C  s>   d}|  ||D ]\}}}| j|}|dur nq|||fS )aq  
        Gets the value for field from environment variables and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains the key, value if the file exists otherwise `None`, and
                a flag to determine whether value is complex.
        N)rj   r   r[   )r,   r.   r/   env_valr{   r   r<   r$   r$   r%   r5     s   
z!EnvSettingsSource.get_field_valuer;   r	   r<   r6   c           	   
   C  s   |  |\}}|s|rO|du r| ||| j}|r|S dS z	| |||}W n ty< } z
|s2|W Y d}~nd}~ww t|trMt|| ||| jS |S |durU|S dS )a  
        Prepare value for the field.

        * Extract value for nested field.
        * Deserialize value to python object for complex field.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains prepared value for the field.

        Raises:
            ValuesError: When There is an error in deserializing value for complex field.
        N)_field_is_complexexplode_env_varsr   r=   rx   r`   ro   r   )	r,   r/   r.   r;   r<   
is_complexallow_parse_failureenv_val_builtr|   r$   r$   r%   r>     s*   
z%EnvSettingsSource.prepare_field_valuer8   type[Any] | Noner9   	list[Any]c                   s   t  fddt|D S )Nc                 3  s    | ]}t | V  qd S r)   )r7   )r   argr9   r$   r%   	<genexpr>      z6EnvSettingsSource._union_is_complex.<locals>.<genexpr>)anyr   )r,   r8   r9   r$   r   r%   _union_is_complex  s   z#EnvSettingsSource._union_is_complextuple[bool, bool]c                 C  sD   |  |rd}d|fS tt|jr | |j|jr d}d|fS dS )za
        Find out if a field is complex, and if so whether JSON errors should be ignored
        FT)FF)r:   r   r   r8   r   r9   )r,   r.   r   r$   r$   r%   r     s   
z#EnvSettingsSource._field_is_complexFieldInfo | Nonekeyc                 C  sF   | r	t t| jrdS | jr!t| jdr!| jj|r!| jj| S dS )a  
        Find the field in a sub model by key(env name)

        By having the following models:

            ```py
            class SubSubModel(BaseSettings):
                dvals: Dict

            class SubModel(BaseSettings):
                vals: list[str]
                sub_sub_model: SubSubModel

            class Cfg(BaseSettings):
                sub_model: SubModel
            ```

        Then:
            next_field(sub_model, 'vals') Returns the `vals` field of `SubModel` class
            next_field(sub_model, 'sub_sub_model') Returns `sub_sub_model` field of `SubModel` class

        Args:
            field: The field.
            key: The key (env name).

        Returns:
            Field if it finds the next field otherwise `None`.
        Nrl   )r   r   r8   rn   rl   r[   )r.   r   r$   r$   r%   
next_field  s
    zEnvSettingsSource.next_fieldr   rA   c                   s  fdd ||D }i }| D ]m\ }t fdd|D s#q jd }|j^}}	}
|}|}|	D ]}||}||i }q:||
}|r||r||\}}|r|z		|
||}W n t
y{ } z
|sq|W Y d}~nd}~ww |||
< q|S )a  
        Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries.

        This is applied to a single field, hence filtering by env_var prefix.

        Args:
            field_name: The field name.
            field: The field.
            env_vars: Environment variables.

        Returns:
            A dictionaty contains extracted values from nested env values.
        c                   s    g | ]\}}}|  j  qS r$   )r   )r   _r   rB   r$   r%   
<listcomp>  s    z6EnvSettingsSource.explode_env_vars.<locals>.<listcomp>c                 3  s    | ]}  |V  qd S r)   )
startswith)r   prefix)r   r$   r%   r     r   z5EnvSettingsSource.explode_env_vars.<locals>.<genexpr>N)rj   rm   r   r   splitr   r   
setdefaultr   r=   rx   )r,   r/   r.   r   prefixesresultr   env_name_without_prefixr   keyslast_keyenv_vartarget_fieldr   r   allow_json_failurer|   r$   )r   r,   r%   r     s8   


z"EnvSettingsSource.explode_env_varsc                 C  s   d| j d| jdS )Nz'EnvSettingsSource(env_nested_delimiter=, env_prefix_len=rP   )r   r   rB   r$   r$   r%   rQ   !  s   
zEnvSettingsSource.__repr__r   )
r'   r(   rV   rW   rX   rY   r   rY   r1   rZ   r1   r   rE   rF   r8   r   r9   r   r1   r6   )r.   r   r1   r   )r.   r   r   r0   r1   r   )r/   r0   r.   r   r   r   r1   rA   rS   )r!   r"   r#   rH   r-   r   r5   r>   r   r   staticmethodr   r   rQ   rT   r$   r$   rL   r%   r   g  s    



(

%.r   c                      sZ   e Zd ZdZeddddfd fddZdddZdddZd  fddZd!ddZ	  Z
S )"DotEnvSettingsSourcezB
    Source class for loading settings values from env files.
    Nr'   r(   env_fileDotenvType | Noneenv_file_encodingrY   rV   rW   rX   r   r1   rZ   c                   sJ   |t kr|n|jd| _|d ur|n|jd| _t |||| d S )Nr   r   )r   r*   r[   r   r   rK   r-   )r,   r'   r   r   rV   rX   r   rL   r$   r%   r-   -  s   	zDotEnvSettingsSource.__init__r   c                 C  s   |  | jS r)   )_read_env_filesrV   rB   r$   r$   r%   r   <  s   z#DotEnvSettingsSource._load_env_varsr6   c                 C  sd   | j }|d u r	i S t|ttjfr|g}i }|D ]}t| }| r/|t	|| j
|d q|S )NencodingrV   )r   r`   r0   r   PathLiker   r   r   updateread_env_filer   )r,   rV   	env_filesdotenv_varsr   env_pathr$   r$   r%   r   ?  s   z$DotEnvSettingsSource._read_env_filesrA   c                   s   t   }g }| jsdd | D }| j D ]-\}}|| jrE|d urE|| jd  }|	| j
^}}|r;||vsA|sE||vrE|||< q|S )Nc                 S  s   g | ]}|  qS r$   r   )r   xr$   r$   r%   r   V  s    z1DotEnvSettingsSource.__call__.<locals>.<listcomp>)rK   rC   rV   r   r   rm   r   rX   r   r   r   )r,   ry   data_lower_keysr   	env_valuer   	first_keyr   rL   r$   r%   rC   Q  s   
zDotEnvSettingsSource.__call__r0   c              	   C  s&   d| j d| jd| jd| jd	S )NzDotEnvSettingsSource(env_file=z, env_file_encoding=z, env_nested_delimiter=r   rP   )r   r   r   r   rB   r$   r$   r%   rQ   f  s   zDotEnvSettingsSource.__repr__)r'   r(   r   r   r   rY   rV   rW   rX   rY   r   rY   r1   rZ   r   )rV   r6   r1   r   rG   rS   )r!   r"   r#   rH   r   r-   r   r   rC   rQ   rT   r$   r$   rL   r%   r   (  s    

r   Fr   	file_pathr   r   rY   rV   r6   r1   r   c                C  s*   t | |pdd}|sdd | D S |S )Nutf8)r   c                 S  r   r$   r   r   r$   r$   r%   r   r  r   z!read_env_file.<locals>.<dictcomp>)r   rm   )r   r   rV   	file_varsr$   r$   r%   r   m  s   r   r8   r   r9   r   c                 C  sB   t dd |D rdS t| }t| p t|p t|dp t|dS )Nc                 s  s    | ]}t |tV  qd S r)   )r`   r   )r   mdr$   r$   r%   r   x  r   z)_annotation_is_complex.<locals>.<genexpr>F__pydantic_core_schema____get_pydantic_core_schema__)r   r   _annotation_is_complex_innerrn   )r8   r9   originr$   r$   r%   r7   w  s   r7   c              	   C  s2   t | ttfr	dS t | ttttttt	fpt
| S )NF)r   r0   bytesr   r   r   tupleset	frozensetr   r   )r8   r$   r$   r%   r     s
   r   )r   r   r   rY   rV   r6   r1   r   r   )r8   r   r1   r6   )<
__future__r   _annotationsr?   r   r   abcr   r   collectionsr   dataclassesr   pathlibr   typingr   r	   r
   r   r   r   r   r   dotenvr   pydanticr   r   r   r    pydantic._internal._typing_extrar   pydantic._internal._utilsr   r   pydantic.fieldsr   typing_extensionsr   r   pydantic_settings.utilsr   pydantic_settings.mainr   r0   r   r   __annotations__rx   r    r&   rI   rU   r}   r   r   r   r7   r   r$   r$   r$   r%   <module>   sB    (,I X BF

