o
    R+ iU                     @  s  d Z ddlm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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 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+m,Z, ddl$m-Z-m.Z.m/Z/m0Z0m1Z1 erddl2m3Z3 	d+d,ddZ4G d d! d!eZ5G d"d# d#eZ6G d$d% d%e5Z7G d&d' d'e5Z8G d(d) d)e5Z9g d*Z:dS )-zBBase classes and core functionality for pydantic-settings sources.    )annotationsN)ABCabstractmethod)asdictis_dataclass)Path)TYPE_CHECKINGAnycastget_args)AliasChoices	AliasPath	BaseModelTypeAdapter)
get_origin)is_model_class)	FieldInfo)typing_objects)is_union_origin   )SettingsError)_lenient_issubclass   )EnvNoneTypeForceDecodeNoDecodePathTypePydanticModel_CliSubCommand)_annotation_is_complex_get_alias_names_get_model_fields_strip_annotated_union_is_complex)BaseSettingsTmodelr   is_requiredboolcli_exit_on_errorbool | 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'|r]|rQdd| dnd}|rYt|t|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(   Z	model_clsZmodel_defaultsubcommands
field_name
field_infoerror_message r;   j/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/pydantic_settings/sources/base.pyget_subcommand$   s*   


r=   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)r?   r.   config_current_state_settings_sources_data)selfr?   r;   r;   r<   __init__Z   s   
z#PydanticBaseSettingsSource.__init__statedict[str, Any]r*   Nonec                 C  
   || _ dS )z
        Record the state of settings from the previous settings sources. This should
        be called right before __call__.
        NrC   )rE   rG   r;   r;   r<   _set_current_state`      
z-PydanticBaseSettingsSource._set_current_statestatesdict[str, dict[str, Any]]c                 C  rJ   )z
        Record the state of settings from all previous settings sources. This should
        be called right before __call__.
        NrD   )rE   rN   r;   r;   r<   _set_settings_sources_datag   rM   z5PydanticBaseSettingsSource._set_settings_sources_datac                 C     | j S )z`
        The current state of the settings, populated by the previous settings sources.
        rK   rE   r;   r;   r<   current_staten      z(PydanticBaseSettingsSource.current_statec                 C  rR   )z=
        The state of all previous settings sources.
        rP   rS   r;   r;   r<   settings_sources_datau   rU   z0PydanticBaseSettingsSource.settings_sources_datafieldr   r8   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.
        Nr;   rE   rW   r8   r;   r;   r<   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   
annotationr2   )rE   rW   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)rE   r8   rW   r_   r`   r;   r;   r<   prepare_field_value   s   z.PydanticBaseSettingsSource.prepare_field_valuec                 C  s6   |rt |j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
        Zenable_decodingF)r   r2   rB   r/   r   jsonloads)rE   r8   rW   r_   r;   r;   r<   ra      s
   

z/PydanticBaseSettingsSource.decode_complex_valuec                 C     d S rA   r;   rS   r;   r;   r<   __call__      z#PydanticBaseSettingsSource.__call__N)r?   r@   )rG   rH   r*   rI   )rN   rO   r*   rI   r*   rH   )r*   rO   rW   r   r8   rX   r*   rY   )rW   r   r*   r'   )
r8   rX   rW   r   r_   r	   r`   r'   r*   r	   )r8   rX   rW   r   r_   r	   r*   r	   )__name__
__module____qualname____doc__rF   rL   rQ   propertyrT   rV   r   r\   r^   rb   ra   rf   r;   r;   r;   r<   r>   U   s     





r>   c                   @  s$   e Zd ZdddZedd	d
ZdS )ConfigFileSourceMixinfilesPathType | Noner*   rH   c                 C  sX   |d u ri S t |ttjfr|g}i }|D ]}t| }| r)|| | q|S rA   )	r0   rX   osPathLiker   
expanduseris_fileupdate
_read_file)rE   rp   varsfile	file_pathr;   r;   r<   _read_files   s   z!ConfigFileSourceMixin._read_filespathr   c                 C  re   rA   r;   )rE   r|   r;   r;   r<   rw      rg   z ConfigFileSourceMixin._read_fileN)rp   rq   r*   rH   )r|   r   r*   rH   )rj   rk   rl   r{   r   rw   r;   r;   r;   r<   ro      s    
ro   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`.
    Nr?   r@   #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   )superrF   defaultsrB   r/   r~   model_fieldsr1   r    r   r-   defaultr   r   Z
model_dump)rE   r?   r~   r8   r9   alias_names_preferred_alias	__class__r;   r<   rF      s"   zDefaultSettingsSource.__init__rW   r   r8   rX   r*   rY   c                 C  rZ   N)N Fr;   r[   r;   r;   r<   r\      rg   z%DefaultSettingsSource.get_field_valuerH   c                 C  rR   rA   )r   rS   r;   r;   r<   rf      s   zDefaultSettingsSource.__call__c                 C  s   | j j d| j dS )Nz%(nested_model_default_partial_update=))r   rj   r~   rS   r;   r;   r<   __repr__   s   zDefaultSettingsSource.__repr__rA   )r?   r@   r~   r)   ri   rh   r*   rX   	rj   rk   rl   rm   rF   r\   rf   r   __classcell__r;   r;   r   r<   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.
    Nr?   r@   init_kwargsrH   r~   r)   c                   s  i | _ t|  |j D ]T\}}t||^}}t|}|jdd}	|	r+||  |@ }
|
rb|r7|d n|}t	 fdd|D d }|d u rQ|	rQ| v rQ|}|d usWJ  |
8  || | j |< q| j 
 fdd| D  t | |d ur|| _d S | jdd| _d S )	Npopulate_by_nameFr   c                 3  s    | ]	}| v r|V  qd S rA   r;   .0aliasZinit_kwarg_namesr;   r<   	<genexpr>  s    z.InitSettingsSource.__init__.<locals>.<genexpr>c                   s   i | ]\}}| v r||qS r;   r;   )r   keyvalr   r;   r<   
<dictcomp>   s    z/InitSettingsSource.__init__.<locals>.<dictcomp>r~   )r   setkeysr   r1   r    r.   r/   addnextrv   r   rF   rB   r~   )rE   r?   r   r~   r8   r9   r   r   Zmatchable_namesZinclude_nameZinit_kwarg_namer   Zprovided_keyr   r   r<   rF     s2   
zInitSettingsSource.__init__rW   r   r8   rX   r*   rY   c                 C  rZ   r   r;   r[   r;   r;   r<   r\   )  rg   z"InitSettingsSource.get_field_valuec                 C  s$   | j rttttf | jS | jS rA   )r~   r   dictrX   r	   Zdump_pythonr   rS   r;   r;   r<   rf   -  s
   zInitSettingsSource.__call__c                 C  s   | j j d| jdS )Nz(init_kwargs=r   )r   rj   r   rS   r;   r;   r<   r   4  s   zInitSettingsSource.__repr__rA   )r?   r@   r   rH   r~   r)   ri   rh   r   r   r;   r;   r   r<   r      s    
(
r   c                      sf   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 )-PydanticBaseEnvSettingsSourceNr?   r@   case_sensitiver)   
env_prefix
str | Noneenv_ignore_emptyenv_parse_none_strenv_parse_enumsr*   rI   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 urF|| _d S | jd| _d S )Nr   Fr   r   r   r   r   )	r   rF   rB   r/   r   r   r   r   r   )rE   r?   r   r   r   r   r   r   r;   r<   rF   9  s   	$z&PydanticBaseEnvSettingsSource.__init__r_   rX   c                 C  s   | j s| S |S rA   )r   lower)rE   r_   r;   r;   r<   _apply_case_sensitiveM  s   z3PydanticBaseEnvSettingsSource._apply_case_sensitiverW   r   r8   list[tuple[str, str, bool]]c                 C  sX  g }t |jttfr|j }n|j}|rct |trX|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n||| |df |rl| jddr|j}t|s{tt|rt|j}tt|rt||jr||| | j| 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.
        r   TFr   r   )r0   Zvalidation_aliasr   r   Zconvert_to_aliaseslistrX   r4   r   lenr
   rB   r/   r]   r   Zis_typealiastyper   r"   Z	__value__r   r#   r2   r   )rE   rW   r8   r9   Zv_aliasr   Z	first_argr]   r;   r;   r<   _extract_field_infoP  s4   

(
	
z1PydanticBaseEnvSettingsSource._extract_field_infofield_valuesrH   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 rA   )r   r   namer;   r<   r     s   " zXPydanticBaseEnvSettingsSource._replace_field_names_case_insensitively.<locals>.<genexpr>)r1   r]   r   r   r   r   r-   hasattrr   r    r   r   r   r0   r   '_replace_field_names_case_insensitively)rE   rW   r   valuesr_   Zsub_model_fieldr]   argsargr   	field_keyZsub_model_field_namealiasesr   Z_searchr;   r   r<   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)r1   r0   r   r   _replace_env_none_type_values)rE   r   r   r   r_   r;   r;   r<   r     s   

z;PydanticBaseEnvSettingsSource._replace_env_none_type_valuesrY   c           	      C  sX   |  ||\}}}|s'| jddr||ks'| ||}|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.
        r   Fr   )r\   rB   r/   r   )	rE   rW   r8   r   r   r`   Zfield_infosZpreferred_keyr   r;   r;   r<   _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 ")r?   r   r1   r   	Exceptionr   r   rj   rb   
ValueErrorr   r0   r   r   r   r   r   )rE   datar8   rW   r   r   r`   er;   r;   r<   rf     sH   


z&PydanticBaseEnvSettingsSource.__call__)NNNNN)r?   r@   r   r)   r   r   r   r)   r   r   r   r)   r*   rI   )r_   rX   r*   rX   )rW   r   r8   rX   r*   r   )rW   r   r   rH   r*   rH   )r   rH   r*   rH   ri   rh   )rj   rk   rl   rF   r   r   r   r   r   rf   r   r;   r;   r   r<   r   8  s    


/
N
r   )ro   r}   r   r   r>   r   )TN)r%   r   r&   r'   r(   r)   r*   r+   );rm   
__future__r   Z_annotationsrc   rr   abcr   r   dataclassesr   r   pathlibr   typingr   r	   r
   r   Zpydanticr   r   r   r   Z pydantic._internal._typing_extrar   Zpydantic._internal._utilsr   Zpydantic.fieldsr   Ztyping_inspectionr   Ztyping_inspection.introspectionr   
exceptionsr   utilsr   typesr   r   r   r   r   r   r   r    r!   r"   r#   Zpydantic_settings.mainr$   r=   r>   ro   r}   r   r   __all__r;   r;   r;   r<   <module>   s:     1m(< _