o
    [۷i[                     @  s  d Z ddlmZ ddl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 ddlmZmZmZ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! 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- ddl$m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 erddl5m6Z6 			d-d.d d!Z7G d"d# d#eZ8G d$d% d%eZ9G d&d' d'e8Z:G d(d) d)e8Z;G d*d+ d+e8Z<g d,Z=dS )/zBBase classes and core functionality for pydantic-settings sources.    )annotationsN)ABCabstractmethod)Sequence)asdictis_dataclass)Path)TYPE_CHECKINGAnycastget_args)AliasChoices	AliasPath	BaseModelTypeAdapter)
get_origin)deep_updateis_model_class)	FieldInfo)is_union_origin   )SettingsError)_lenient_issubclass   )EnvNoneTypeEnvPrefixTargetForceDecodeNoDecodePathTypePydanticModel_CliSubCommand)_annotation_is_complex_get_alias_names_get_field_metadata_get_model_fields_resolve_type_alias_strip_annotated_union_is_complex)BaseSettingsTmodelr   is_requiredboolcli_exit_on_errorbool | None_suppress_errors'list[SettingsError | SystemExit] | NonereturnPydanticModel | Nonec                 C  s   t | }|du rt|r|jd}t|tr|}|du rd}g }t| D ]\}}t|j	v rCt
| |dur>t
| |  S || q'|rh|rQdd| dnd}	|rYt|	nt|	}
|du rc|
||
 dS )a  
    Get the subcommand from a model.

    Args:
        model: The model to get the subcommand from.
        is_required: Determines whether a model must have subcommand set and raises error if not
            found. Defaults to `True`.
        cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
            Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.

    Returns:
        The subcommand model if found, otherwise `None`.

    Raises:
        SystemExit: When no subcommand is found and is_required=`True` and cli_exit_on_error=`True`
            (the default).
        SettingsError: When no subcommand is found and is_required=`True` and
            cli_exit_on_error=`False`.
    Nr,   Tz#Error: CLI subcommand is required {z, }z@Error: CLI subcommand is required but no subcommands were found.)typer   model_configget
isinstancer+   r$   itemsr    metadatagetattrappendjoin
SystemExitr   )r)   r*   r,   r.   	model_clsmodel_defaultsubcommands
field_name
field_infoerror_messageerr rD   T/home/ubuntu/vllm_env/lib/python3.10/site-packages/pydantic_settings/sources/base.pyget_subcommand%   s0   



rF   c                   @  s   e Zd ZdZd(ddZd)d
dZd*ddZed+ddZed,ddZ	e
d-ddZd.ddZd/d!d"Zd0d#d$Ze
d+d%d&Zd'S )1PydanticBaseSettingsSourcezi
    Abstract base class for settings sources, every settings source classes should inherit from it.
    settings_clstype[BaseSettings]c                 C  s   || _ |j| _i | _i | _d S N)rH   r4   config_current_state_settings_sources_data)selfrH   rD   rD   rE   __init__a   s   
z#PydanticBaseSettingsSource.__init__statedict[str, Any]r0   Nonec                 C  
   || _ dS )z
        Record the state of settings from the previous settings sources. This should
        be called right before __call__.
        NrL   )rN   rP   rD   rD   rE   _set_current_stateg      
z-PydanticBaseSettingsSource._set_current_statestatesdict[str, dict[str, Any]]c                 C  rS   )z
        Record the state of settings from all previous settings sources. This should
        be called right before __call__.
        NrM   )rN   rW   rD   rD   rE   _set_settings_sources_datan   rV   z5PydanticBaseSettingsSource._set_settings_sources_datac                 C     | j S )z`
        The current state of the settings, populated by the previous settings sources.
        rT   rN   rD   rD   rE   current_stateu      z(PydanticBaseSettingsSource.current_statec                 C  r[   )z=
        The state of all previous settings sources.
        rY   r\   rD   rD   rE   settings_sources_data|   r^   z0PydanticBaseSettingsSource.settings_sources_datafieldr   r@   str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 that contains the value, key and a flag to determine whether value is complex.
        NrD   rN   r`   r@   rD   rD   rE   get_field_value   s   z*PydanticBaseSettingsSource.get_field_valuer+   c                 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.
        )r!   
annotationr8   )rN   r`   rD   rD   rE   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)rg   decode_complex_value)rN   r@   r`   rh   ri   rD   rD   rE   prepare_field_value   s   z.PydanticBaseSettingsSource.prepare_field_valuec                 C  s8   |rt t|v s| jddu rt|jvr|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
        enable_decodingF)r   r#   rK   r5   r   r8   jsonloads)rN   r@   r`   rh   rD   rD   rE   rj      s
   
z/PydanticBaseSettingsSource.decode_complex_valuec                 C     d S rJ   rD   r\   rD   rD   rE   __call__      z#PydanticBaseSettingsSource.__call__N)rH   rI   )rP   rQ   r0   rR   )rW   rX   r0   rR   r0   rQ   )r0   rX   r`   r   r@   ra   r0   rb   )r`   r   r0   r+   )
r@   ra   r`   r   rh   r
   ri   r+   r0   r
   )r@   ra   r`   r   rh   r
   r0   r
   )__name__
__module____qualname____doc__rO   rU   rZ   propertyr]   r_   r   re   rg   rk   rj   rp   rD   rD   rD   rE   rG   \   s     





rG   c                   @  s&   e Zd Zdddd	ZedddZdS )ConfigFileSourceMixinFfilesPathType | None
deep_merger+   r0   rQ   c                 C  s   |d u ri S t |trt |tr|g}i }|D ].}t |tr#t|}n|}t |tr.| }| s3q| |}|r@t||}q|| q|S rJ   )	r6   r   ra   r   
expanduseris_file
_read_filer   update)rN   rz   r|   varsfile	file_pathupdating_varsrD   rD   rE   _read_files   s$   



z!ConfigFileSourceMixin._read_filespathr   c                 C  ro   rJ   rD   )rN   r   rD   rD   rE   r      rq   z ConfigFileSourceMixin._read_fileN)F)rz   r{   r|   r+   r0   rQ   )r   r   r0   rQ   )rt   ru   rv   r   r   r   rD   rD   rD   rE   ry      s    ry   c                      sB   e Zd ZdZdd fddZdddZdddZdddZ  ZS )DefaultSettingsSourcea  
    Source class for loading default object values.

    Args:
        settings_cls: The Settings class.
        nested_model_default_partial_update: Whether to allow partial updates on nested model default object fields.
            Defaults to `False`.
    NrH   rI   #nested_model_default_partial_updater-   c                   s   t  | i | _|d ur|n| jdd| _| jrN|j D ]0\}}t||^}}|d }t	t
|jr>t|j| j|< qtt
|jrM|j | j|< qd S d S )Nr   Fr   )superrO   defaultsrK   r5   r   model_fieldsr7   r"   r   r3   defaultr   r   
model_dump)rN   rH   r   r@   rA   alias_names_preferred_alias	__class__rD   rE   rO      s"   zDefaultSettingsSource.__init__r`   r   r@   ra   r0   rb   c                 C  rc   N)N FrD   rd   rD   rD   rE   re     rq   z%DefaultSettingsSource.get_field_valuerQ   c                 C  r[   rJ   )r   r\   rD   rD   rE   rp     s   zDefaultSettingsSource.__call__c                 C  s   | j j d| j dS )Nz%(nested_model_default_partial_update=))r   rt   r   r\   rD   rD   rE   __repr__	  s   zDefaultSettingsSource.__repr__rJ   )rH   rI   r   r-   rs   rr   r0   ra   	rt   ru   rv   rw   rO   re   rp   r   __classcell__rD   rD   r   rE   r      s    	

r   c                      sD   e Zd ZdZ	d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.
    NrH   rI   init_kwargsrQ   r   r-   c                   s$  i | _ t|  |j D ][\}}t||^}}t|}|jddp*|jdd}	|	r2||  |@ }
|
ri|r>|d n|}t	 fdd|D d }|d u rX|	rX| v rX|}|d us^J  |
8  || | j |< q| j 
 fdd| D  t | |d ur|| _d S | jd	d| _d S )
Npopulate_by_nameFvalidate_by_namer   c                 3  s    | ]	}| v r|V  qd S rJ   rD   .0aliasinit_kwarg_namesrD   rE   	<genexpr>+  s    z.InitSettingsSource.__init__.<locals>.<genexpr>c                   s   i | ]\}}| v r||qS rD   rD   )r   keyvalr   rD   rE   
<dictcomp>5  s    z/InitSettingsSource.__init__.<locals>.<dictcomp>r   )r   setkeysr   r7   r"   r4   r5   addnextr   r   rO   rK   r   )rN   rH   r   r   r@   rA   r   r   matchable_namesinclude_nameinit_kwarg_namer   provided_keyr   r   rE   rO     s6   
zInitSettingsSource.__init__r`   r   r@   ra   r0   rb   c                 C  rc   r   rD   rd   rD   rD   rE   re   >  rq   z"InitSettingsSource.get_field_valuec                 C  s$   | j rttttf | jS | jS rJ   )r   r   dictra   r
   dump_pythonr   r\   rD   rD   rE   rp   B  s
   zInitSettingsSource.__call__c                 C  s   | j j d| jdS )Nz(init_kwargs=r   )r   rt   r   r\   rD   rD   rE   r   I  s   zInitSettingsSource.__repr__rJ   )rH   rI   r   rQ   r   r-   rs   rr   r   r   rD   rD   r   rE   r     s    
*
r   c                      sh   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d-d#d$Zd.d%d&Z	  Z
S )/PydanticBaseEnvSettingsSourceNrH   rI   case_sensitiver-   
env_prefix
str | Noneenv_prefix_targetEnvPrefixTarget | Noneenv_ignore_emptyenv_parse_none_strenv_parse_enumsr0   rR   c                   s   t  | |d ur|n| jdd| _|d ur|n| jdd| _|d ur(|n| jdd| _|d ur6|n| jdd| _|d urD|n| jd| _|d urT|| _	d S | jd	| _	d S )
Nr   Fr   r   r   variabler   r   r   )
r   rO   rK   r5   r   r   r   r   r   r   )rN   rH   r   r   r   r   r   r   r   rD   rE   rO   N  s   
$z&PydanticBaseEnvSettingsSource.__init__rh   ra   c                 C  s   | j s| S |S rJ   )r   lower)rN   rh   rD   rD   rE   _apply_case_sensitivef  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}|rs| jdv r| jnd}t |trf|D ]>}t |trC|	|| 
|| t|dkr>dndf q&t |trdtt|d }|	|| 
|| t|dkr`dndf q&n|	|| 
|| df |r| jdds| jddrtt|j}| jd	v r| jnd}tt|rt||jr|	|| 
|| df |S |	|| 
|| 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.
        )r   allr   r   TFr   r   r   )r   r   )r6   validation_aliasr   r   convert_to_aliasesr   r   listra   r:   r   lenr   rK   r5   r&   r%   rf   r   r   r'   r8   )	rN   r`   r@   rA   v_aliasr   r   	first_argrf   rD   rD   rE   _extract_field_infoi  s>   

"
 z1PydanticBaseEnvSettingsSource._extract_field_infofield_valuesrQ   c                   s  i }|  D ]\ }d}|j}tt|jr3t|}t|dkr3td|v r3|D ]
}|dur2|} nq(|r:t|ds?|| < q|j}	d}
|	  D ]\}}t	||\}} fdd|D }t
|d }
re nqH|
sm|| < q|durt|jtrt|tr| ||||
< 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'}}}
        Nr   r   c                 3  s$    | ]}|     kr|V  qd S rJ   )r   r   namerD   rE   r     s   " zXPydanticBaseEnvSettingsSource._replace_field_names_case_insensitively.<locals>.<genexpr>)r7   rf   r   r   r   r   r3   hasattrr   r"   r   r   r   r6   r   '_replace_field_names_case_insensitively)rN   r`   r   valuesrh   sub_model_fieldrf   argsargr   	field_keysub_model_field_namealiasesr   _searchrD   r   rE   r     sD   

zEPydanticBaseEnvSettingsSource._replace_field_names_case_insensitivelyfield_valuec                 C  sJ   i }|  D ]\}}t|tst|ts|n| |||< qd||< q|S )ze
        Recursively parse values that are of "None" type(EnvNoneType) to `None` type(None).
        N)r7   r6   r   r   _replace_env_none_type_values)rN   r   r   r   rh   rD   rD   rE   r     s   

z;PydanticBaseEnvSettingsSource._replace_env_none_type_valuesrb   c           	      C  sn   |  ||\}}}|du r2|s2| jdds| jddr!||ks2| ||}|d ^}}|||fS |||fS )a8  
        Gets the value, the preferred alias key for model creation, and a flag to determine whether value
        is complex.

        Note:
            In V3, this method should either be made public, or, this method should be removed and the
            abstract method get_field_value should be updated to include a "use_preferred_alias" flag.

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

        Returns:
            A tuple that contains the value, preferred key and a flag to determine whether value is complex.
        Nr   Fr   r   )re   rK   r5   r   )	rN   r`   r@   r   r   ri   field_infospreferred_keyr   rD   rD   rE   _get_resolved_field_value  s   

z7PydanticBaseEnvSettingsSource._get_resolved_field_valuec                 C  s  i }| j j D ]\}}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r| j
d urrt|trk| |}nt|trrd }| jst|tr| ||||< q|||< q|S )Nzerror getting value for field "z" from source ""zerror parsing value for field ")rH   r   r7   r   	Exceptionr   r   rt   rk   
ValueErrorr   r6   r   r   r   r   r   )rN   datar@   r`   r   r   ri   erD   rD   rE   rp     sH   


z&PydanticBaseEnvSettingsSource.__call__)NNNNNN)rH   rI   r   r-   r   r   r   r   r   r-   r   r   r   r-   r0   rR   )rh   ra   r0   ra   )r`   r   r@   ra   r0   r   )r`   r   r   rQ   r0   rQ   )r   rQ   r0   rQ   rs   rr   )rt   ru   rv   rO   r   r   r   r   r   rp   r   rD   rD   r   rE   r   M  s    


5
N
r   )ry   r   r   r   rG   r   )TNN)
r)   r   r*   r+   r,   r-   r.   r/   r0   r1   )>rw   
__future__r   _annotationsrm   abcr   r   collections.abcr   dataclassesr   r   pathlibr   typingr	   r
   r   r   pydanticr   r   r   r    pydantic._internal._typing_extrar   pydantic._internal._utilsr   r   pydantic.fieldsr   typing_inspection.introspectionr   
exceptionsr   utilsr   typesr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   pydantic_settings.mainr(   rF   rG   ry   r   r   r   __all__rD   rD   rD   rE   <module>   s<    $$
7m(> p