o
    i-                     @  s   d dl mZ d dlZd dlmZ d dlmZmZm	Z	m
Z
 d dlmZ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 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" erhd dl#m$Z$ G dd deZ%dgZ&dS )    )annotationsN)Mapping)TYPE_CHECKINGAnyget_args
get_origin)JsonTypeAdapterValidationError)deep_updateis_model_class)is_pydantic_dataclass)	FieldInfo)is_union_origin   )_lenient_issubclass   )PydanticBaseEnvSettingsSource)EnvNoneType)_annotation_contains_types_annotation_enum_name_to_val_get_model_fields_union_is_complexparse_env_vars)BaseSettingsc                      s   e Zd ZdZ							d3d4 fddZd5ddZd6ddZd7d!d"Zd8d$d%Z	d9d:d)d*Z	d;d-d.Z
d<d/d0Zd=d1d2Z  ZS )>EnvSettingsSourcezN
    Source class for loading settings values from environment variables.
    Nsettings_clstype[BaseSettings]case_sensitivebool | None
env_prefix
str | Noneenv_nested_delimiterenv_nested_max_split
int | Noneenv_ignore_emptyenv_parse_none_strenv_parse_enumsreturnNonec	           	        st   t  |||||| |d ur|n| jd| _|d ur|n| jd| _| jp)dd | _t| j| _	| 
 | _d S )Nr"   r#   r      )super__init__configgetr"   r#   maxsplitlenr    env_prefix_len_load_env_varsenv_vars)	selfr   r   r    r"   r#   r%   r&   r'   	__class__ m/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_settings/sources/providers/env.pyr,   &   s   zEnvSettingsSource.__init__Mapping[str, str | None]c                 C  s   t tj| j| j| jS N)r   osenvironr   r%   r&   r4   r7   r7   r8   r2   ?   s   z EnvSettingsSource._load_env_varsfieldr   
field_namestrtuple[Any, str, bool]c                 C  s>   d}|  ||D ]\}}}| j|}|dur nq|||fS )ah  
        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 that contains the value (`None` if not found), key, and
                a flag to determine whether value is complex.
        N)_extract_field_infor3   r.   )r4   r>   r?   env_val	field_keyenv_namevalue_is_complexr7   r7   r8   get_field_valueB   s   
z!EnvSettingsSource.get_field_valuevaluer   rF   boolc           
   
   C  s   |  |\}}| jrt|j|}|du r|n|}|s|rgt|tr#|S |du r5| ||| j}|r3|S dS z	| |||}W n t	yT }	 z
|sJ|	W Y d}	~	nd}	~	ww t|t
ret|| ||| jS |S |durq| ||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_complexr'   r   
annotation
isinstancer   explode_env_varsr3   decode_complex_value
ValueErrordictr   _coerce_env_val_strict)
r4   r?   r>   rH   rF   
is_complexallow_parse_failureenum_valenv_val_builter7   r7   r8   prepare_field_valueW   s4   

z%EnvSettingsSource.prepare_field_valuetuple[bool, bool]c                 C  sB   |  |rd}d|fS tt|jrt|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)field_is_complexr   r   rK   r   metadata)r4   r>   rS   r7   r7   r8   rJ      s   
z#EnvSettingsSource._field_is_complexFieldInfo | Any | NonekeyFieldInfo | Nonec                 C  s   |sdS t |tr|jn|}t|D ]}| |||}|r!|  S qt|s*t|rnt|}| D ];\}}	| 	|	|D ]0\}
}}
|du sG|rV||ksO||krU|	    S q<|
 |
 ksf|
 |
 krl|	    S q<q2dS )aK  
        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).
            case_sensitive: Whether to search for key case sensitively.

        Returns:
            Field if it finds the next field otherwise `None`.
        N)rL   r   rK   r   
next_fieldr   r   r   itemsrB   lower)r4   r>   r\   r   rK   type_type_has_keyfieldsr?   f_rE   r7   r7   r8   r^      s*     zEnvSettingsSource.next_fieldr3   dict[str, Any]c                   s  j si S |j}|tu ptt|t}fdd||D }i }| D ]\ }zt fdd|D }	W n	 ty@   Y q&w  t	|	d }
|

j j^ }}|}|}|D ]}||j}t|tro||i }qZ||j}|s||r|r|r|\}}jrt|j|}|du r|n|}nd\}}|rz	|||}W n ty } z
|s|W Y d}~nd}~ww t|tr||vst|tr|| i krۈ||||< 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 dictionary contains extracted values from nested env values.
        c                   s    g | ]\}}}|  j  qS r7   )r"   ).0re   rE   r=   r7   r8   
<listcomp>   s    z6EnvSettingsSource.explode_env_vars.<locals>.<listcomp>c                 3  s    | ]
}  |r|V  qd S r:   )
startswith)rg   prefix)rE   r7   r8   	<genexpr>   s    z5EnvSettingsSource.explode_env_vars.<locals>.<genexpr>N)TT)r"   rK   rP   r   r   rB   r_   nextStopIterationr0   splitr/   r^   r   rL   
setdefaultrJ   r'   r   rN   rO   r   rQ   )r4   r?   r>   r3   annis_dictprefixesresultrC   rj   env_name_without_prefixkeyslast_keyenv_vartarget_fieldr\   rR   allow_json_failurerT   rV   r7   )rE   r4   r8   rM      s\   



z"EnvSettingsSource.explode_env_varsc                 C  s   z5| j dr*t|tr-|dur0|| jkr|W S t|jtfdds3t|j	|W S W |S W |S W |S W |S  t
y?   Y |S w )a   
        Coerce environment string values based on field annotation if model config is `strict=True`.

        Args:
            field: The field.
            value: The value to coerce.

        Returns:
            The coerced value if successful, otherwise the original value.
        strictNT)is_instance)r-   r.   rL   r@   r&   r   rK   r   r	   validate_pythonr
   )r4   r>   rH   r7   r7   r8   rQ   	  s$   
z(EnvSettingsSource._coerce_env_val_strictc                 C  s   | j j d| jd| jdS )Nz(env_nested_delimiter=z, env_prefix_len=))r6   __name__r"   r1   r=   r7   r7   r8   __repr__  s   zEnvSettingsSource.__repr__)NNNNNNN)r   r   r   r   r    r!   r"   r!   r#   r$   r%   r   r&   r!   r'   r   r(   r)   )r(   r9   )r>   r   r?   r@   r(   rA   )
r?   r@   r>   r   rH   r   rF   rI   r(   r   )r>   r   r(   rX   r:   )r>   r[   r\   r@   r   r   r(   r]   )r?   r@   r>   r   r3   r9   r(   rf   )r>   r]   rH   r   r(   r   )r(   r@   )r~   
__module____qualname____doc__r,   r2   rG   rW   rJ   r^   rM   rQ   r   __classcell__r7   r7   r5   r8   r   !   s&    



.
5
?r   )'
__future__r   _annotationsr;   collections.abcr   typingr   r   r   r   pydanticr   r	   r
   pydantic._internal._utilsr   r   pydantic.dataclassesr   pydantic.fieldsr   typing_inspection.introspectionr   utilsr   baser   typesr   r   r   r   r   r   pydantic_settings.mainr   r   __all__r7   r7   r7   r8   <module>   s&      
