o
    i2^                     @   s  U d Z ddlZddlZddlZddl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mZmZmZmZ ddlZddlZddlZddlmZ ddlmZ edZeee
f Zeed< G dd	 d	eZd
eee
e
f  dee de
ddfddZ ddd
e
dee de
de
fddZ!d
e
deeef ddfddZ"d
e
dee dee de#de$e ddfddZ%dTdede&defd d!Z'dUd#e(d$e&de
fd%d&Z)d'e*de&fd(d)Z+d*e
d+eee(f ddfd,d-Z,e	j-d.d/d0Z.dd1d2d3d4dd5d#e
d6e#d7e#d8e#d9e#d:e#d;eee#  defd<d=Z/d#e
d6e#d7e#d8e#d9e#d:e#d;ee# defd>d?Z0G d@d/ d/ej1Z1G dAdB dBeej2Z3defdCdDZ4d
eee(f deee(f fdEdFZ5dGedeedHe
f gedHe
f f fdIdJZ6dKedefdLdMZ7dNedOedefdPdQZ8dNedOeddfdRdSZ9dS )VzCommon utilities for the SDK.    N)AnyCallable	FrozenSetOptionalUnionget_args
get_origin)alias_generators)	TypeAliaszgoogle_genai._common
StringDictc                   @   s   e Zd ZdZdS )ExperimentalWarningz"Warning for experimental features.N)__name__
__module____qualname____doc__ r   r   Z/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/google/genai/_common.pyr   &   s    r   datakeysvaluereturnc           	      C   s4  |du rdS t |dd D ]\}}|dr|dd }| durB|| vrBt|tr8dd tt|D | |< n
td| d| t|trg| durgt | | D ]\}}t|||d	 d ||  qQ dS | dur~| | D ]}t|||d	 d | qo dS |d
r|dd }| dur|| vri g| |< | durt| | d ||d	 d |  dS | dur| |i } q| dur| 	|d }|dur|sdS ||krdS t|t
rt|t
r|| dS td|d  d| d| d|d dkrt| t
rt|t
r| | dS || |d < dS dS )a9  Examples:

  set_value_by_path({}, ['a', 'b'], v)
    -> {'a': {'b': v}}
  set_value_by_path({}, ['a', 'b[]', c], [v1, v2])
    -> {'a': {'b': [{'c': v1}, {'c': v2}]}}
  set_value_by_path({'a': {'b': [{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'd'], v3)
    -> {'a': {'b': [{'c': v1, 'd': v3}, {'c': v2, 'd': v3}]}}
  N[]c                 S   s   g | ]}i qS r   r   ).0_r   r   r   
<listcomp>=   s    z%set_value_by_path.<locals>.<listcomp>zvalue z$ must be a list given an array path    [0]r   z+Cannot set value for an existing key. Key: z; Existing value: z; New value: ._self)	enumerateendswith
isinstancelistrangelen
ValueErrorset_value_by_path
setdefaultgetdictupdate)	r   r   r   ikeykey_namejdexisting_datar   r   r   r)   *   sj   



 
r)   default_valuer5   c                   s   dgkr| S t D ]r\}| s   S |dr7|dd }|| v r3 fdd| | D   S    S |dra|dd }|| v r]| | r]t| | d	 d
 d  d  S    S || v rj| | } qt| trzt| |rzt| |} q   S | S )zExamples:

  get_value_by_path({'a': {'b': v}}, ['a', 'b'])
    -> v
  get_value_by_path({'a': {'b': [{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'c'])
    -> [v1, v2]
  r!   r   Nr   c                    s&   g | ]}t |d  d  dqS )r   Nr4   )get_value_by_path)r   r2   r5   r.   r   r   r   r      s    z%get_value_by_path.<locals>.<listcomp>r   r   r   r   r4   )r"   r#   r6   r$   	BaseModelhasattrgetattr)r   r   r5   r/   r0   r   r7   r   r6   t   s2   






r6   pathsc           
      C   s   |  D ]W\}}|d}|d}t }d}t|D ]\}}	|	dkr'|} nq|dkrSt||krSt|t|D ]}|| }	|	dkrR|	dsR|	dsR||	 q9t| ||d| qdS )a#  Moves values from source paths to destination paths.

  Examples:
    move_value_by_path(
      {'requests': [{'content': v1}, {'content': v2}]},
      {'requests[].*': 'requests[].request.*'}
    )
      -> {'requests': [{'request': {'content': v1}}, {'request': {'content':
      v2}}]}
  r    r   *r   r   r   N)	itemssplitsetr"   r'   r&   r#   add_move_value_recursive)
r   r;   source_path	dest_pathsource_keys	dest_keysexclude_keyswildcard_idxr.   r/   r   r   r   move_value_by_path   s$   


rH   rD   rE   key_idxrF   c                    sB  |t |krdS || }|dr9|dd }| v r3t | tr5 | D ]}t||||d  q&dS dS dS |dkrt trfddt  D } fdd	|D }	|	 D ]$\}
}g }||d D ]}|dkrt||
 qh|| qht	 || q\|D ]}
 |
= qdS dS | v rt | |||d  dS dS )
z>Recursively moves values from source path to destination path.Nr   r   r   r<   c                    s"   g | ]}| d s| vr|qS )r   )
startswithr   k)rF   r   r   r      s    z)_move_value_recursive.<locals>.<listcomp>c                    s   i | ]}| | qS r   r   rK   )r   r   r   
<dictcomp>       z)_move_value_recursive.<locals>.<dictcomp>)
r'   r#   r$   r%   rA   r,   r   r=   appendr)   )r   rD   rE   rI   rF   r/   r0   itemkeys_to_movevalues_to_moverL   vnew_dest_keysdkr   )r   rF   r   rA      sD   



rA   T	snake_strconvertc                 C   s   |s| S t ddd | S )z>Converts a snake_case string to CamelCase, if convert is True.z_([a-zA-Z])c                 S   s   |  d S )Nr   )groupupper)matchr   r   r   <lambda>   s    z&maybe_snake_to_camel.<locals>.<lambda>)resub)rV   rW   r   r   r   maybe_snake_to_camel   s   r^   Fobjconvert_keysc                    s^   t | tjrt| jdd S t | tr fdd|  D S t | tr- fdd| D S | S )a  Recursively converts a given object to a dictionary.

  If the object is a Pydantic model, it uses the model's `model_dump()` method.

  Args:
    obj: The object to convert.
    convert_keys: Whether to convert the keys from snake case to camel case.

  Returns:
    A dictionary representation of the object, a list of objects if a list is
    passed, or the object itself if it is not a dictionary, list, or Pydantic
    model.
  T)exclude_nonec                    s    i | ]\}}t | t|qS r   )r^   convert_to_dict)r   r/   r   r`   r   r   rM     s    z#convert_to_dict.<locals>.<dictcomp>c                    s   g | ]}t | qS r   )rb   )r   rP   rc   r   r   r     rN   z#convert_to_dict.<locals>.<listcomp>)r$   pydanticr8   rb   
model_dumpr,   r=   r%   )r_   r`   r   rc   r   rb     s   


rb   
annotationc                 C   s   t | }t| }|turdS |rt|dkrdS |d }t |}t|}|tur*dS |r2t|dkr4dS |\}}|tu o@|tju S )zChecks if the given annotation is list[dict[str, typing.Any]]

  or typing.List[typing.Dict[str, typing.Any]].

  This maps to Struct type in the API.
  Fr   r      )r   r   r%   r'   r,   strtypingr   )rf   outer_origin
outer_argsinner_annotationinner_origin
inner_argskey_type
value_typer   r   r   _is_struct_type  s   rq   modelresponsec                 C   s   t | }|D ]g\}}dd | j D }|| jvr%||vr%|| q|||}| j| j}t|tu r?t	|d }t
|trQt|turQt|| qt
|t rot|r[q|D ]}t
|trntt	|d | q]qdS )zfRemoves extra fields from the response that are not in the model.

  Mutates the response in place.
  c                 S   s   i | ]\}}|j |qS r   )alias)r   r/   
field_infor   r   r   rM   H  s    z(_remove_extra_fields.<locals>.<dictcomp>r   N)r%   r=   model_fieldspopr+   rf   ri   r   r   r   r$   r,   _remove_extra_fieldsrq   )rr   rs   
key_valuesr/   r   	alias_maprf   rP   r   r   r   rx   =  s,   


rx   Tr8   )boundrg   d         indent_levelindent_deltamax_len	max_itemsdepthvisitedr   r   r   r   r   r   c             
   C   s  |du rt  }t| }||v rdS |dk rdS t t||g }d| }d||  }	t| tjr| jj}
g }tt	| j
}|D ]>}t	| j
| }|jsLq?zt| |}W n	 ty\   Y q?w |du rbq?t||| ||||d |d}||	 | d|  q?|s|
 d	S |
 d
d| d| d S t| trd| v r| dd}d| dS t| S t| trt| |krt| d|d  dd  dS t| S t| tjjrb| sdS |dkrt|  dt| dkrdnd }d| dS t| |krdt|  dS g }z
t|  td}W n ty    t|  }Y nw |D ]1}| | }t||| ||||d |d}t||| ||||d |d}||	 | d|  q#dd| d| d S t| tttfrvt| ||||||dS t| }|dd|	 S )z-Returns a representation of the given object.Nz<... Circular reference ...>r   z<... Max depth ...> r   r   =z()z(
,

)z"""z\"\"\"   r   z...'z{} items z{<... z at Max depth ...>}z
<dict len=>)r/   z: z{
})	frozensetidr%   r$   rd   r8   	__class__r   sortedtyperv   reprr:   AttributeError_pretty_reprrO   joinrh   replacebytesr'   collectionsabcMappingr   	TypeErrortupler?   _format_collection)r_   r   r   r   r   r   r   obj_idindentnext_indent_strcls_namer=   fields
field_nameru   r   
value_represcapeditem_count_strsorted_keysrL   rS   k_reprv_reprraw_reprr   r   r   r   i  s   	
 

""		r   c                C   sn  t | tr
d}| }n&t | trd}t| }nt | tr't| }| r$d}nd}n	tdt|  |s:|d |d  S |dkr[t| dd	t|dk  }	|d  d
|	 d|d  S d| }
d||  }g }tt||}t|D ]}|| }|	|t
||| ||||d |d  qrt||kr|	| d
t||  d |d  dd| d|
 |d   S )z(Formats a collection (list, tuple, set).)[])(r   ){r   )zset(r   zUnsupported collection type: r   r   r   r   z<... z at Max depth ...>r   r   z more items ...>r   r   )r$   r%   r   r?   r(   r   r'   minr&   rO   r   r   )r_   r   r   r   r   r   r   bracketsinternal_objr   r   r   elementsnum_to_showr.   elemr   r   r   r     sR   



*r   c                       s   e Zd Zejejdddddddejfd	Z	de
f fddZed	eje d
ee
ef dee
ef defddZdee
ef fddZ  ZS )r8   Tr   forbidbase64)	alias_generatorpopulate_by_namefrom_attributesprotected_namespacesextraarbitrary_types_allowedser_json_bytesval_json_bytesignored_typesr   c                    s(   zt | W S  ty   t   Y S w N)r   	Exceptionsuper__repr__selfr   r   r   r   4  s
   
zBaseModel.__repr__clsrs   kwargsc                C   s^   |d uo d|v o |d d uo t |d to d|d v o |d d }|s(t| | | |}|S )Nconfiginclude_all_fields)r$   r,   rx   model_validate)r   rs   r   should_skip_removing_fieldsvalidated_responser   r   r   _from_response:  s   


	

zBaseModel._from_responsec                 C   s   | j dddS )NTjson)ra   mode)re   r   r   r   r   to_json_dictV  s   zBaseModel.to_json_dict)r   r   r   rd   
ConfigDictr	   to_camelri   TypeVarmodel_configrh   r   classmethodTyper{   r,   objectr   r   __classcell__r   r   r   r   r8   %  s0    

c                       s.   e Zd ZdZededef fddZ  ZS )CaseInSensitiveEnumzCase insensitive enum.r   r   c                    s   z| |   W S  tyI   z	| |  W  Y S  tyH   t| d| j  zt | |}t||_	||_
|W  Y  Y S    Y Y Y d S w w )Nz is not a valid )rY   KeyErrorlowerwarningswarnr   r   __new__rh   _name__value_)r   r   unknown_enum_valr   r   r   	_missing_]  s    

zCaseInSensitiveEnum._missing_)r   r   r   r   r   r   r   r   r   r   r   r   r   Z  s     r   c                  C   s0   t j  d} t jdd }|  d| S )z]Composes a timestamped unique name.

  Returns:
      A string representing a unique name.
  z%Y%m%d%H%M%Sr   r~   r   )datetimenowstrftimeuuiduuid4hex)	timestamp	unique_idr   r   r   timestamped_unique_nameq  s   r   c                 C   s   i }t | ts	| S |  D ]e\}}t |tr!t|d||< qt |tjr.| ||< qt |tr:t	|||< qt |t
rntdd |D rQdd |D ||< tdd |D rddd |D ||< qdd |D ||< q|||< q|S )	a  Converts unserializable types in dict to json.dumps() compatible types.

  This function is called in models.py after calling convert_to_dict(). The
  convert_to_dict() can convert pydantic object to dict. However, the input to
  convert_to_dict() is dict mixed of pydantic object and nested dict(the output
  of converters). So they may be bytes in the dict and they are out of
  `ser_json_bytes` control in model_dump(mode='json') called in
  `convert_to_dict`, as well as datetime deserialization in Pydantic json mode.

  Returns:
    A dictionary with json.dumps() incompatible type (e.g. bytes datetime)
    to compatible type (e.g. base64 encoded string, isoformat date string).
  asciic                 s   s    | ]}t |tV  qd S r   )r$   r   r   rS   r   r   r   	<genexpr>  s    z.encode_unserializable_types.<locals>.<genexpr>c                 S   s   g | ]
}t |d qS )r   )r   urlsafe_b64encodedecoder   r   r   r   r     s    z/encode_unserializable_types.<locals>.<listcomp>c                 s   s    | ]	}t |tjV  qd S r   )r$   r   r   r   r   r   r     s    c                 S   s   g | ]}|  qS r   )	isoformatr   r   r   r   r         c                 S   s   g | ]}t |qS r   )encode_unserializable_typesr   r   r   r   r     r   )r$   r,   r=   r   r   r   r   r   r   r   r%   all)r   processed_datar/   r   r   r   r   r   |  s(   





r   message.c                    s*   dt dtf dt dtf f fdd}|S )z&Experimental warning, only warns once.func.r   c                    s0   dt  dtdtdtf fdd}|S )NFargsr   r   c                     s&   sdt jtdd  | i |S )NTrg   )r   category
stacklevel)r   r   r   )r   r   )r   r   warning_doner   r   wrapper  s   z8experimental_warning.<locals>.decorator.<locals>.wrapper)	functoolswrapsr   )r   r  r   )r   r  r   	decorator  s    z'experimental_warning.<locals>.decorator)r   r   )r   r  r   r  r   experimental_warning  s   &r  key_strc                 C   s   |  dd S )z?Normalizes a key for case-insensitive and snake/camel matching.r   r   )r   r   )r  r   r   r   _normalize_key_for_matching  s   r	  target_dictupdate_dictc                 C   s   i }dd |   D }| D ]@\}}t|}||v r || }n|}t|tr9t| |tr9t| | |||< qt|trKt| |trK|||< q|||< q|S )a  Aligns the keys of update_dict to the case of target_dict keys.

  Args:
      target_dict: The dictionary with the target key casing.
      update_dict: The dictionary whose keys need to be aligned.

  Returns:
      A new dictionary with keys aligned to target_dict's key casing.
  c                 S   s   i | ]}t ||qS r   )r	  )r   r/   r   r   r   rM     s    
z"align_key_case.<locals>.<dictcomp>)r   r=   r	  r$   r,   r+   align_key_caser%   )r
  r  aligned_update_dicttarget_keys_mapr/   r   normalized_update_keyaligned_keyr   r   r   r    s*   





r  c              
   C   s   t | |}| D ]G\}}|| v r%t| | tr%t|tr%t| | | q	|| v rLt| | t|sLtd| dt| |  dt| d || |< q	|| |< q	dS )a  Recursively updates a target dictionary with values from an update dictionary.

  We don't enforce the updated dict values to have the same type with the
  target_dict values except log warnings.
  Users providing the update_dict should be responsible for constructing correct
  data.

  Args:
      target_dict (dict): The dictionary to be updated.
      update_dict (dict): The dictionary containing updates.
  zType mismatch for key 'z'. Existing type: z, new type: z. Overwriting.N)r  r=   r$   r,   recursive_dict_updater   loggerwarning)r
  r  r  r/   r   r   r   r   r    s&   



r  )T)F):r   r   collections.abcr   r   enumr  loggingr\   ri   r   r   r   r   r   r   r   r   r   rd   r	   typing_extensionsr
   	getLoggerr  r,   rh   r   __annotations__Warningr   r%   r)   r6   rH   intr?   rA   boolr^   r   rb   r   rq   rx   r   r{   r   r   r8   Enumr   r   r   r  r	  r  r  r   r   r   r   <module>   s   $

K
*$
8!)
	
~	
>5"&

)