o
    %gu                     @   s  d Z ddlZddlmZmZ ddlmZm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 ejrIddlZddlZddlmZ ddlmZ e
d	Zejd
krsejZejejfZ ddlm!Z! nej"ZejfZ ddl#m!Z! dddej$de%de%de&fddZ'dej$de%fddZ(dej$de)de%fddZ*dej$de+e%ef de,e+e%ef  fddZ-dej$de%fdd Z.dej/fd!d"Z0d#eej1 dej2fd$d%Z3d&eee,ej1 ej1e,ej2 f  de,ej2 fd'd(Z4dej$d)eeee%ef   dee,ej5  fd*d+Z6eej7ej8ej1f Z9dej$d,ee9 dej7fd-d.Z:dej$d/ee,ej7 e,ej8 e9f dee,e% e,ej7 f fd0d1Z;dej$d/eeej<ej=ej7f  de,ej7 fd2d3Z>d4e+e%ef fd5d6Z?	dfd7d8d4e+e%ef dej$d9ee+e%ef  d:e)fd;d<Z@d=edej$dejAfd>d?ZBd@eejCef de!e+e%ef  fdAdBZDdej$d@eejCef deejA fdCdDZEdEej$d@eejFef deejG fdFdGZHdej$deejI fdHdIZJdej$d@e,e de,ejI fdJdKZKdej$dLe%fdMdNZLdej$dOe%fdPdQZMdej$dRe%fdSdTZNdej$dLe%fdUdVZOdWZPdXZQdYZRdZZSdej$d[e+fd\d]ZTdej$dLeee%ejUejVejWf  fd^d_ZXdej$d`e%deejYe%f fdadbZZdej$dce[de%fdddeZ\dS )gz"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasOptionalUnion   )_api_client)typeszgoogle_genai._transformers)   
   )	TypeGuard   )collection_hierarchy_depthclientresource_namecollection_identifierr   c                C   s   | | d o| d| dd |k}| jrX| dr!|S | dr/d| j d| S | | drDd| j d| j d| S |rVd| j d| j d| d| S |S |ra| d| S |S )a|  Prepends resource name with project, location, collection_identifier if needed.

  The collection_identifier will only be prepended if it's not present
  and the prepending won't violate the collection hierarchy depth.
  When the prepending condition doesn't meet, returns the input
  resource_name.

  Args:
    client: The API client.
    resource_name: The user input resource name to be completed.
    collection_identifier: The collection identifier to be prepended. See
      collection identifiers in https://google.aip.dev/122.
    collection_hierarchy_depth: The collection hierarchy depth. Only set this
      field when the resource has nested collections. For example,
      `users/vhugo1802/events/birthday-dinner-226`, the collection_identifier is
      `users` and collection_hierarchy_depth is 4. See nested collections in
      https://google.aip.dev/122.

  Example:

    resource_name = 'cachedContents/123'
    client.vertexai = True
    client.project = 'bar'
    client.location = 'us-west1'
    _resource_name(client, 'cachedContents/123',
      collection_identifier='cachedContents')
    returns: 'projects/bar/locations/us-west1/cachedContents/123'

  Example:

    resource_name = 'projects/foo/locations/us-central1/cachedContents/123'
    # resource_name = 'locations/us-central1/cachedContents/123'
    client.vertexai = True
    client.project = 'bar'
    client.location = 'us-west1'
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns: 'projects/foo/locations/us-central1/cachedContents/123'

  Example:

    resource_name = '123'
    # resource_name = 'cachedContents/123'
    client.vertexai = False
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns 'cachedContents/123'

  Example:
    resource_name = 'some/wrong/cachedContents/resource/name/123'
    resource_prefix = 'cachedContents'
    client.vertexai = False
    # client.vertexai = True
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns: 'some/wrong/cachedContents/resource/name/123'

  Returns:
    The completed resource name.
  /r
   	projects/z
locations//locations/)
startswithcountvertexaiprojectlocation)r   r   r   r   $should_prepend_collection_identifier r   \/mnt/skqttb/ctump_chatbot/chatbot/lib/python3.10/site-packages/google/genai/_transformers.py_resource_name2   s$   E

 r    modelc                 C   s   |st d| jr3|ds|ds|dr|S d|v r.|dd\}}d| d| S d| S |dr:|S |d	rA|S d| S )
Nzmodel is required.r   models/publishers/r   r
   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr   r   split)r   r!   	publishermodel_idr   r   r   t_model   s&   



r(   
api_clientbase_modelsreturnc                 C   s   | j r	|rdS dS |rdS dS )Nzpublishers/google/modelsmodelstunedModels)r   )r)   r*   r   r   r   t_models_url   s   r.   responsec                 C   s   |sg S | d}|d ur|S | d}|d ur|S | d}|d ur%|S | dd ur5| dd u r5g S td td| g S )Nr,   r-   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)r)   r/   r,   tuned_modelspublisher_modelsr   r   r   t_extract_models   s&   


r9   c                 C   sj   t | |}|s	d S |dr| jrd| j d| j d| S |dr3| jr3d| j d| j d| S |S )Nr#   r   r   r   r"   z/publishers/google/)r(   r   r   r   r   )r)   r!   r   r   r   t_caches_model   s   
r:   c                 C   s   z	dd l }|j}W n ty   d }Y nw t }|d ur#t| |js(| jdkr2| j|dd d}n	| j|dd d}|	d |
 }tj||dS )	Nr   RGBAPNG)formatz	image/pngJPEGz
image/jpeg)	mime_typedata)PIL.PngImagePluginPngImagePluginImportErrorioBytesIO
isinstancePngImageFilemodesaveseekreadr   Blob)imgPILrB   bytesior?   r@   r   r   r   pil_to_blob   s$   



rP   partc                 C   s   z
dd l }|jj}W n ty   d }Y nw | d u rtdt| tr)tj| dS |d ur:t| |r:tjt| dS t| tj	rT| j
rF| jsJtdtjj| j
| jdS t| tr_tj| S t| tjrg| S tdt|  )Nr   zcontent part is required.)text)inline_dataz$file uri and mime_type are required.)file_urir?   zUnsupported content part type: )	PIL.ImageImagerC   r$   rF   strr   PartrP   Fileurir?   from_uridictmodel_validatetype)rQ   rN   	PIL_Imager   r   r   t_part   s*   

r`   partsc                 C   s@   | d u st | tr| stdt | trdd | D S t| gS )Nzcontent parts are required.c                 S   s   g | ]}t |qS r   )r`   .0rQ   r   r   r   
<listcomp>  s    zt_parts.<locals>.<listcomp>)rF   listr$   r`   ra   r   r   r   t_parts  s
   

rg   predictionsc                 C   sP   |sd S g }|D ]}| dr%|tjtj|d d |d d dd q|S )NimagegcsUri
imageBytes)gcs_uriimage_bytes)ri   )r3   appendr   GeneratedImagerV   )r   rh   images
predictionr   r   r   t_image_predictions#  s   


rr   contentc                 C   s   |d u rt dt|tjr|S t|tr@ztj|W S  tjy?   tj|}|j	r6tj
|gd Y S tj|gd Y S w t|tjrW|j	rPtj
|gdS tj|gdS tj|dS )Nzcontent is required.rf   )r$   rF   r   Contentr\   r]   pydanticValidationErrorrX   function_callModelContentUserContent)r   rs   possible_partr   r   r   	t_content:  s,   
r{   contentsc                    s   t |tr fdd|D }nt |g} jrJg }|D ]+}|d urGt |tr-tj|}|jd urG|jD ]}|j	rA|
|j	 q5td q5q|S |S )Nc                    s   g | ]}t  |qS r   )r{   )rc   rs   r   r   r   rd   Z  s    z(t_contents_for_embed.<locals>.<listcomp>z/Non-text part found, only returning text parts.)rF   re   r{   r   r\   r   rt   r]   ra   rR   rn   r4   r5   )r   r|   transformed_contents
text_partsrs   rQ   r   r}   r   t_contents_for_embedU  s&   



r   c                    s  |d u st |tr|stdt |tst| |gS z
dd l}|jj W n ty/   d  Y nw g }g }dttj	t
f dttj	 f fdd}dtjdtfddd	ttj dtffd
ddttj dttj ffdddttj dttj dtj	ffdd}|D ]I}t |tjst |tr|| t |tr|tj|d q|| q||r|||| qt |tr|tj| qtdt| || |S )Nzcontents are required.r   rQ   r+   c                    sp   t | tst | tjs d urt |  st | tjrdS t | tr6z	tj|  W dS  tjy5   Y dS w dS )NTF)	rF   rW   r   rY   rX   r\   r]   ru   rv   rQ   )r_   r   r   _is_part  s    


zt_contents.<locals>._is_partc                 S   s   | j  S N)rw   r   r   r   r   _is_user_part  s   z!t_contents.<locals>._is_user_partra   c                    s   t  fdd| D S )Nc                 3   s    | ]} |V  qd S r   r   rb   r   r   r   	<genexpr>  s    z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>)allrf   r   r   r   _are_user_parts  s   z#t_contents.<locals>._are_user_partsresultaccumulated_partsc                    s>   |sd S |   |rtj|dntj|d g |d d < d S )Nrf   )rn   r   ry   rx   )r   r   )r   r   r   $_append_accumulated_parts_as_content  s   
z8t_contents.<locals>._append_accumulated_parts_as_contentcurrent_partc                    sB   t |}||kr|| d S  | | |g|d d < d S r   )r`   rn   )r   r   r   )r   r   r   r   r   _handle_current_part  s
   
z(t_contents.<locals>._handle_current_partrf   zUnsupported content type: )rF   re   r$   r{   rU   rV   rC   r	   r   PartUnionDictr   r   rX   boolrt   rn   ry   r\   r]   r^   )r   r|   rN   r   r   r   r   rs   r   )r_   r   r   r   r   
t_contentsq  sV   
&




r   schemac                 C   s   |  dddkrd| d< | d= dS d| v rO| d D ]7}d|v rN|d dkrNd| d< | d ddi t| d dkrN| d d  D ]\}}|| |< qB| d= qdS dS )	a  Process null fields in the schema so it is compatible with OpenAPI.

  The OpenAPI spec does not support 'type: 'null' in the schema. This function
  handles this case by adding 'nullable: True' to the null field and removing
  the {'type': 'null'} entry.

  https://swagger.io/docs/specification/v3_0/data-models/data-types/#null

  Example of schema properties before and after handling null fields:
    Before:
      {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "total_area_sq_mi": {
          "anyOf": [
            {
              "type": "integer"
            },
            {
              "type": "null"
            }
          ],
          "default": None,
          "title": "Total Area Sq Mi"
        }
      }

    After:
      {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "total_area_sq_mi": {
          "type": "integer",
          "nullable": true,
          "default": None,
          "title": "Total Area Sq Mi"
        }
      }
  r^   NnullTnullableanyOfr
   r   )r3   removelenitems)r   itemkeyvalr   r   r   handle_null_fields  s   ,

r   Torder_propertiesdefsr   c                   s  |j s ddurtd ddkr dd  dddur* d d< |du rC di }| D ]
\}}t||| q8t   d	d}|durl||d
d  }t|	 D ]}||  |< q` d	=  dd}	|	dur|	D ]!}|d	d}
|
du rt||| qx||
d
d  }|	
| qxdd |	D  d< dS  dd}t|tr|j}| } dd}|dur|dkr|g d<  d= ntd|dkr: dd}|du rdS | D ](\}}|d	d}
|
du rt||| q||
d
d  }t||| |||< qt| dkr4|r6t fdddD r8t|	 }| d< dS dS dS dS |dkrt dd}|du rLdS |d	d}
|
du r_t||| dS ||
d
d  }t||| | d< dS dS )a{  Updates the schema and each sub-schema inplace to be API-compatible.

  - Inlines the $defs.

  Example of a schema before and after (with mldev):
    Before:

    `schema`

    {
        'items': {
            '$ref': '#/$defs/CountryInfo'
        },
        'title': 'Placeholder',
        'type': 'array'
    }


    `defs`

    {
      'CountryInfo': {
        'properties': {
          'continent': {
              'title': 'Continent',
              'type': 'string'
          },
          'gdp': {
              'title': 'Gdp',
              'type': 'integer'}
          },
        }
        'required':['continent', 'gdp'],
        'title': 'CountryInfo',
        'type': 'object'
      }
    }

    After:

    `schema`
     {
        'items': {
          'properties': {
            'continent': {
              'title': 'Continent',
              'type': 'string'
            },
            'gdp': {
              'title': 'Gdp',
              'type': 'integer'
            },
          }
          'required':['continent', 'gdp'],
          'title': 'CountryInfo',
          'type': 'object'
        },
        'type': 'array'
    }
  defaultNzIDefault value is not supported in the response schema for the Gemini API.titlePlaceholderLiteralEnumany_ofr   z$defs$refzdefs/c                 S   s   g | ]}d |vr|qS )r   r   )rc   r   r   r   r   rd   ~  s    z"process_schema.<locals>.<listcomp>r^   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr
   c                 3   s    | ]}| vV  qd S r   r   )rc   ordering_keyr   r   r   r     s
    
z!process_schema.<locals>.<genexpr>)property_orderingpropertyOrderingr   ARRAYr   )r   r3   r$   popr   process_schemar   r%   re   keysrn   rF   r   valueupperr   r   )r   r   r   r   _
sub_schema
schema_refref
schema_keyr   ref_keyschema_typer   r   nameproperty_namesr   r   r   r     s   C




	

r   r   c                    sr    D ]}t |jtstd|j dt|j qG  fdddtj}| }t	|| |d d }t
j|S )NzEnum member z value must be a string, got c                          e Zd ZU  ed< dS )z"_process_enum.<locals>.PlaceholderplaceholderN__name__
__module____qualname____annotations__r   r   r   r   Placeholder     
 r   r   r   )rF   r   rW   	TypeErrorr   r^   ru   	BaseModelmodel_json_schemar   r   Schemar]   )r   r   memberr   enum_schemar   r   r   _process_enum  s   

r   originc                 C   s   t | totdd | D S )zEVerifies the schema is of type dict[str, Any] for mypy type checking.c                 s   s    | ]}t |tV  qd S r   )rF   rW   )rc   r   r   r   r   r     s    

z(_is_type_dict_str_any.<locals>.<genexpr>)rF   r\   r   r   r   r   r   _is_type_dict_str_any  s   r   c                    sN   sd S t  trt rt | dd tj S t  tr$t | S t  tjrKt tt kr8t	d j
dd}t|| dd tj|S t  tsjt  trjt tjrj  }t||  tj|S t  tst  tst  tst tv rG  fdddtj}| }t||  |d d	 }tj|S t	d
  )NFr   zUnsupported schema type.T)exclude_unsetc                       r   )zt_schema.<locals>.Placeholderr   Nr   r   r   r   r   r     r   r   r   r   zUnsupported schema type: )rF   r\   r   r   r   r   r]   r   r   r$   
model_dumpr   r^   
issubclassru   r   r   VersionedUnionTypetyping
get_origin_UNION_TYPES)r   r   r   r   r   r   r   t_schema  sF   




r   r   c                 C   s   |sd S t |tjr|S t |trtjtjtj|dddS t |trYd|v rY|d d urYd|d v rY|d d d urYd|d d v rYtjtjtj|d d ddddS tdt	| )N)
voice_name)prebuilt_voice_config)voice_configr   r   r   zUnsupported speechConfig type: )
rF   r   SpeechConfigrW   VoiceConfigPrebuiltVoiceConfigr\   r3   r$   r^   )r   r   r   r   r   t_speech_config  s6   

	r   c                 C   s:   |sd S t |st |rtjtjj| |dgdS |S )N)r   callablefunction_declarations)inspect
isfunctionismethodr   ToolFunctionDeclarationfrom_callable)r   r   r   r   r   t_tool  s   r   c                 C   st   |sg S t jg d}g }|D ]!}t| |}|d ur/|jr*|jd ur*| j|j7  _q|| q|jr8|| |S )Nr   )r   r   r   r   rn   )r   r   function_tooltoolstooltransformed_toolr   r   r   t_tools-  s$   



r   r   c                 C   s   t | |ddS )NcachedContents)r   )r    )r   r   r   r   r   t_cached_content_nameF  s   r   srcc                 C   s@   | drtjd|gdS | drtjd|dS td| )Ngs://jsonlr=   rl   bq://bigqueryr=   bigquery_urizUnsupported source: )r   r   BatchJobSourcer$   )r   r   r   r   r   t_batch_job_sourceJ  s   

r   destc                 C   s>   | drtjd|dS | drtjd|dS td| )Nr   r   r   r   r   r   zUnsupported destination: )r   r   BatchJobDestinationr$   )r   r   r   r   r   t_batch_job_destinationY  s   

r   c                 C   sD   | j s|S d}t||r|dd S | r|S td| d)Nz:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$r   r   zInvalid batch job name: .)r   rematchr%   isdigitr$   )r   r   patternr   r   r   t_batch_job_nameh  s   r  g      ?g      4@g      @g      ?structc                 C   s   | d }r^d|v r^|}d}t}| ddkrE|tkr&td| d| | jd|i d	}t| ||7 }t|t t	}| ddks| d
 }rYtd| d| d| | dS |S )Nr   z/operations/g        doneTz
Operation z timed out.
GET)http_methodpathrequest_dicterrorz failed with error: z.
r/   )
r3   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)r)   r  r   	operationtotal_secondsdelay_secondsr
  r   r   r   t_resolve_operation{  s.   

r  c                 C   s   t |tjr
|j}nt |tjr|j}nt |tjr&|jd ur$|jj}nd }|d u r.tdt |t	s=tdt
| d|dra|dd }td|}|d u rZtd| |d	}|S |drm|dd }|S )
NzFile name is required.z"Could not convert object of type `z` to a file name.zhttps://zfiles/r
   z	[a-z0-9]+z&Could not extract file name from URI: r   )rF   r   rY   r   VideorZ   GeneratedVideovideor$   rW   r^   r   r%   r   r   group)r)   r   suffixr   r   r   r   t_file_name  s0   





r  statusc                 C   sf   |dkrt jjS |dkrt jjS |dkrt jjS |dkr t jjS t jD ]}t|j|kr0|  S q#|S )NSTATE_UNSPECIFIEDCREATINGACTIVEFAILED)r   JobStateJOB_STATE_UNSPECIFIEDJOB_STATE_RUNNINGJOB_STATE_SUCCEEDEDJOB_STATE_FAILEDrW   r   )r)   r  stater   r   r   t_tuning_job_status  s   
r)  r@   c                 C   s   t |ts|S t|dS )Nascii)rF   bytesbase64	b64encodedecode)r)   r@   r   r   r   t_bytes  s   
r/  r   )]__doc__r,  collections.abcr   r   r   r   r   r   rD   loggingr   sysr  r   builtin_typesr   r   r   r   r	   TYPE_CHECKINGrU   rN   ru    r   	getLoggerr4   version_info	UnionTyper   r   r   _UnionGenericAliastyping_extensionsBaseApiClientrW   intr    r(   r   r.   r\   re   r9   r:   rL   rP   r   rX   r`   rg   ro   rr   rt   ContentDictContentTyper{   r   ContentListUnionContentListUnionDictr   r   r   r   r   SchemaUnionDictr   r   SpeechConfigUnionDictr   r   r   r   r   r   r   r   r  r  r  r  r  r  rY   r  r  r  r#  r)  r+  r/  r   r   r   r   <module>   s8  


]


 




e>

 #
(
.
"

#
