o
    Zht                     @   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,ej- f dee,ej-  fddZ.dej$de%fdd Z/dej0fd!d"Z1d#eej2 dej3fd$d%Z4d&eee,ej2 ej2e,ej3 f  de,ej3 fd'd(Z5dej$d)eeee%ef   dee,ej6  fd*d+Z7eej8ej9ej2f Z:dej$d,ee: dej8fd-d.Z;dej$d/ee,ej8 e,ej9 e:f dee,e% e,ej8 f fd0d1Z<dej$d/eeej=ej>ej8f  de,ej8 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<ZAd=edej$dejBfd>d?ZCd@eejDef de!e+e%ef  fdAdBZEdej$d@eejDef deejB fdCdDZFdEej$d@eejGef deejH fdFdGZIdej$deejJ fdHdIZKdej$d@e,e de,ejJ fdJdKZLdej$dLe%fdMdNZMdej$dOe%fdPdQZNdej$dRe%fdSdTZOdej$dLe%fdUdVZPdWZQdXZRdYZSdZZTdej$d[e+fd\d]ZUdej$dLeee%ejVejWejXf  fd^d_ZYdej$d`e%deejZe%f fdadbZ[d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   Z$should_prepend_collection_identifier r   Q/var/www/html/lang_env/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    Z	publisherZ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| dS | dd ur| dS | dd ur(| dS | dd ur8| dd u r8g S td td| g S )Nr)   r*   ZpublisherModelsZhttpHeadersZjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)r&   r,   r   r   r   t_extract_models   s   



r1   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   
r2   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   ZRGBAZPNG)formatz	image/pngZJPEGz
image/jpeg)	mime_typedata)ZPIL.PngImagePluginPngImagePluginImportErrorioBytesIO
isinstanceZPngImageFilemodesaveseekreadr   Blob)ZimgPILr6   Zbytesior4   r5   r   r   r   pil_to_blob   s$   



rA   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)Zinline_dataz$file uri and mime_type are required.)Zfile_urir4   zUnsupported content part type: )	PIL.ImageImager7   r#   r:   strr   PartrA   Fileurir4   Zfrom_uridictmodel_validatetype)rB   r@   	PIL_Imager   r   r   t_part   s*   

rN   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   )rN   .0rB   r   r   r   
<listcomp>  s    zt_parts.<locals>.<listcomp>)r:   listr#   rN   rO   r   r   r   t_parts  s
   

rU   predictionsc                 C   sP   |sd S g }|D ]}| dr%|tjtj|d d |d d dd q|S )NimageZgcsUriZ
imageBytes)gcs_uriZimage_bytes)rW   )r-   appendr   GeneratedImagerE   )r   rV   ZimagesZ
predictionr   r   r   t_image_predictions  s   


r[   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.rT   )r#   r:   r   ContentrJ   rK   pydanticValidationErrorrG   function_callModelContentUserContent)r   r\   Zpossible_partr   r   r   	t_content1  s,   
rc   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   )rc   )rQ   r\   r   r   r   rR   Q  s    z(t_contents_for_embed.<locals>.<listcomp>z/Non-text part found, only returning text parts.)r:   rS   rc   r   rJ   r   r]   rK   rO   rC   rY   r.   r/   )r   rd   Ztransformed_contentsZ
text_partsr\   rB   r   re   r   t_contents_for_embedL  s&   



rf   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   rB   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)	r:   rF   r   rH   rG   rJ   rK   r^   r_   rB   )rM   r   r   _is_part}  s    


zt_contents.<locals>._is_partc                 S   s   | j  S N)r`   rg   r   r   r   _is_user_part  s   z!t_contents.<locals>._is_user_partrO   c                    s   t  fdd| D S )Nc                 3   s    | ]} |V  qd S ri   r   rP   rj   r   r   	<genexpr>  s    z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>)allrT   rk   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 )NrT   )rY   r   rb   ra   )ro   rp   )rn   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 ri   )rN   rY   )ro   rp   rr   )rq   rn   rj   r   r   _handle_current_part  s
   
z(t_contents.<locals>._handle_current_partrT   zUnsupported content type: )r:   rS   r#   rc   rD   rE   r7   r	   r   PartUnionDictr   r   rG   boolr]   rY   rb   rJ   rK   rL   )r   rd   r@   ro   rp   rh   rs   r\   r   )rM   rq   rn   rj   r   
t_contentsh  sV   
&




rv   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"
        }
      }
  rL   NnullTZnullableanyOfr
   r   )r-   removelenitems)rw   itemkeyvalr   r   r   handle_null_fields  s   ,

r   Torder_propertiesdefsr   c                   s  |j s dd  ddurtd ddkr! dd  dddur0 d d< |du rI di }| D ]
\}}t||| q>t   d	d}|durr||d
d  }t|	 D ]}||  |< qf d	=  dd}	|	dur|	D ]!}|d	d}
|
du rt||| q~||
d
d  }|	
| q~d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rA dd}|du rdS | D ])\}}|d	d}
|
du rt||| q||
d
d  }t||| |||< qt| dkr;|r=t fdddD r?t|	 }| d< dS dS dS dS |dkr{ dd}|du rSdS |d	d}
|
du rft||| dS ||
d
d  }t||| | d< dS dS )ai  Updates the schema and each sub-schema inplace to be API-compatible.

  - Removes the `title` field from the schema if the client is not vertexai.
  - 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': {
                'type': 'string'
            },
            'gdp': {
                'type': 'integer'}
            },
          }
          'required':['continent', 'gdp'],
          'type': 'object'
        },
        'type': 'array'
    }
  titleNdefaultzIDefault value is not supported in the response schema for the Gemini API.ZPlaceholderLiteralEnumany_ofry   z$defs$refzdefs/c                 S   s   g | ]}d |vr|qS )r   r   )rQ   r}   r   r   r   rR   u  s    z"process_schema.<locals>.<listcomp>rL   constSTRINGenumzLiteral values must be strings.ZOBJECT
propertiesr
   c                 3   s    | ]}| vV  qd S ri   r   )rQ   Zordering_keyrw   r   r   rl     s
    
z!process_schema.<locals>.<genexpr>)property_orderingZpropertyOrderingr   ZARRAYr|   )r   popr-   r#   r|   process_schemar   r$   rS   keysrY   r:   r   valueupperr{   rm   )rw   r   r   r   _Z
sub_schemaZ
schema_refrefZ
schema_keyr   Zref_keyZschema_typer   r   nameZproperty_namesr   r   r   r     s   A





	

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   )r:   r   rF   	TypeErrorr   rL   r^   	BaseModelmodel_json_schemar   r   SchemarK   )r   r   memberr   Z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 ri   )r:   rF   )rQ   r~   r   r   r   rl     s    

z(_is_type_dict_str_any.<locals>.<genexpr>)r:   rJ   rm   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)Zexclude_unsetc                       r   )zt_schema.<locals>.Placeholderr   Nr   r   r   r   r   r     r   r   r   r   zUnsupported schema type: )r:   rJ   r   r   r   r   rK   r   r   r#   Z
model_dumpr   rL   
issubclassr^   r   r   VersionedUnionTypetyping
get_origin_UNION_TYPES)r   r   rw   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: )
r:   r   SpeechConfigrF   ZVoiceConfigZPrebuiltVoiceConfigrJ   r-   r#   rL   )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   ToolZ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   rY   )r   r   Zfunction_toolZtoolsZtoolZtransformed_toolr   r   r   t_tools$  s$   



r   r   c                 C   s   t | |ddS )NZcachedContents)r   )r   )r   r   r   r   r   t_cached_content_name=  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r3   rX   bq://bigqueryr3   Zbigquery_urizUnsupported source: )r   r   ZBatchJobSourcer#   )r   r   r   r   r   t_batch_job_sourceA  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   ZBatchJobDestinationr#   )r   r   r   r   r   t_batch_job_destinationP  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_name_  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)Zhttp_methodpathZrequest_dicterrorz failed with error: z.
r,   )
r-   !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   Z	operationtotal_secondsZdelay_secondsr   r   r   r   t_resolve_operationr  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   )r:   r   rH   r   VideorI   GeneratedVideoZvideor#   rF   rL   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 )NZSTATE_UNSPECIFIEDZCREATINGZACTIVEZFAILED)r   JobStateZJOB_STATE_UNSPECIFIEDZJOB_STATE_RUNNINGZJOB_STATE_SUCCEEDEDZJOB_STATE_FAILEDrF   r   )r&   r   stater   r   r   t_tuning_job_status  s   
r   r5   c                 C   s   t |ts|S t|dS )Nascii)r:   bytesbase64	b64encodedecode)r&   r5   r   r   r   t_bytes  s   
r   ri   )^__doc__r   collections.abcr   r   r   r   r   r   r8   loggingr   sysr   r   Zbuiltin_typesr   r   r   r   r	   TYPE_CHECKINGrD   r@   r^    r   	getLoggerr.   version_info	UnionTyper   r   r   _UnionGenericAliasZtyping_extensionsZBaseApiClientrF   intr   r%   ru   r+   rJ   rS   Z	ModelDictr1   r2   r?   rA   rt   rG   rN   rU   rZ   r[   r]   ZContentDictZContentTyperc   rf   ZContentListUnionZContentListUnionDictrv   r   r   r   r   ZSchemaUnionDictr   r   ZSpeechConfigUnionDictr   r   r   r   r   r   r   r   r   r   r   r   r   r   rH   r   r   r   r   r   r   r   r   r   r   r   <module>   s8  


]






e>

 #
(
.
"

#
