o
    0Xxi_                     @   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mZmZmZmZ ejrAddlZddlZddlmZ ddlmZ ejd	krbejjZejejjfZnejZejf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%de&ej' fddZ(dejdefddZ)dej*fdd Z+eej,ej-ed!f Z.dejd"e.dej,fd#d$Z/dejd%ee&e.f de&ej, fd&d'Z0dejd(eeeeef   de&ej1 fd)d*Z2eej3ej4e.f Z5dejd+e5fd,d-Z6dejd.ee&ej3 e&ej4 e5f fd/d0Z7dejd.ee&ej3 e&ej4 e5f fd1d2Z8d3e%eef fd4d5Z9		dcd6d7d3e%eef deej d8ee%eef  d9e#fd:d;Z:	ddd<edeej dej;fd=d>Z<dejd?eej=ef deej; fd@dAZ>dBejd?eej?ef deej@ fdCdDZAdejdejBfdEdFZCdejd?e&e de&ejB fdGdHZDdejdIefdJdKZEdejdLefdMdNZFdejdOefdPdQZGdejdIefdRdSZHdTZIdUZJdVZKdWZLdejdXe%fdYdZZMdejdIeeejNf fd[d\ZOdejd]edejPfd^d_ZQdejd`eRdefdadbZSdS )ez"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasOptionalUnion   )_api_client)types)   
      )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   Y/home/air/biblejyuku/back/venv/lib/python3.10/site-packages/google/genai/_transformers.py_resource_name-   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   sX   |sg S | dd ur| dS | dd ur| dS | dd ur(| dS td)Nr+   r,   publisherModelsz!Cannot determine the models type.)getr#   )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   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PILr:   bytesior7   r8   r   r   r   pil_to_blob   s$   



rH   zPIL.Image.Imagepartc                 C   s   z
dd l }|jj}W n ty   d }Y nw |stdt|tr'tj|dS |d ur8t||r8tjt|dS t|tj	rR|j
rD|jsHtdtjj|j
|jdS |S )Nr   zcontent part is required.)text)inline_dataz$file uri and mime_type are required.)file_urir7   )	PIL.ImageImager;   r#   r>   strr   PartrH   Fileurir7   from_uri)r   rI   rF   	PIL_Imager   r   r   t_part   s"   
rU   partsc                    s8   |d u rt dt|tr fdd|D S t |gS )Nzcontent parts are required.c                       g | ]}t  |qS r   )rU   ).0rI   r   r   r   
<listcomp>      zt_parts.<locals>.<listcomp>)r#   r>   listrU   )r   rV   r   rY   r   t_parts   s
   
r]   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)r_   )r0   appendr   GeneratedImagerN   )r   r^   images
predictionr   r   r   t_image_predictions	  s   


rh   contentc                 C   sF   |st dt|tjr|S t|trtj|S tjdt| |dS )Nzcontent is required.user)rolerV   )r#   r>   r   Contentdictmodel_validater]   )r   ri   r   r   r   	t_content   s   
ro   contentsc                    sd    j rt|tr fdd|D S  j rt |jd jgS t|tr, fdd|D S t |gS )Nc                    s   g | ]}t  |jd  jqS )r   )ro   rV   rJ   rX   ri   rY   r   r   rZ   3  s    z(t_contents_for_embed.<locals>.<listcomp>r   c                    rW   r   ro   rq   rY   r   r   rZ   7  r[   )r   r>   r\   ro   rV   rJ   r   rp   r   rY   r   t_contents_for_embed-  s   
rt   c                    s4   |st dt|tr fdd|D S t |gS )Nzcontents are required.c                    rW   r   rr   rq   rY   r   r   rZ   C  r[   zt_contents.<locals>.<listcomp>)r#   r>   r\   ro   rs   r   rY   r   
t_contents<  s
   
ru   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"
        }
      }
  typeNnullTnullableanyOfr
   r   )r0   removelenitems)rv   itemkeyvalr   r   r   handle_null_fieldsH  s   ,

r   Torder_propertiesdefsr   c                   s
  |r|j s dd  ddurtd ddkr# dd  dddur2 d d< |du rK di }| D ]
\}}t||| q@t   d	drs| d	d
d  }t|	 D ]}||  |< qg d	=  dd}|dur|j std|D ]!}|d	d}	|	du rt||| q||	d
d  }|
| qd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rI dd}|du rdS | D ])\}}|d	d}	|	du rt||| q||	d
d  }t||| |||< qt| dkrC|rEt fdddD rGt|	 }| d< dS dS dS dS |
dkr dd}|du r[dS |d	d}	|	du rnt||| 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.PlaceholderLiteralEnumany_ofrz   z$defs$refzdefs/zAAnyOf is not supported in the response schema for the Gemini API.c                 S   s   g | ]}d |vr|qS )r   r   )rX   r~   r   r   r   rZ     s    z"process_schema.<locals>.<listcomp>rw   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr
   c                 3   s    | ]}| vV  qd S Nr   )rX   ordering_keyrv   r   r   	<genexpr>  s
    
z!process_schema.<locals>.<genexpr>)property_orderingpropertyOrderingr   ARRAYr}   )r   popr0   r#   r}   process_schemar   r$   r\   keysrd   r>   r   valueupperr|   all)rv   r   r   r   _
sub_schemaref
schema_keyr   ref_keyschema_typer   r   name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   Placeholder1     
 r   r   r   )r>   r   rO   	TypeErrorr   rw   pydantic	BaseModelmodel_json_schemar   r   Schemarn   )r   r   memberr   enum_schemar   r   r   _process_enum'  s   

r   originc                    sF   sd S t  trt | dd tj S t  tr t | S t  tjrGt tt kr4td j	dd}t|| dd tj|S t  t
sft  trft tjrf  }t||  tj|S t  t
s|t  ts|t  ts|t 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: )r>   rm   r   r   r   rn   r   r   r#   
model_dumpr   rw   
issubclassr   r   r   VersionedUnionTypetyping
get_origin_UNION_TYPES)r   r   rv   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rCd|v rCd|d v rCt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   SpeechConfigrO   VoiceConfigPrebuiltVoiceConfigrm   r0   r#   rw   )r   r   r   r   r   t_speech_configh  s0   

	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   sb   |sg S t jg d}g }|D ]}t| |}|jr!| j|j7  _q|| q|jr/|| |S )Nr   )r   r   r   r   rd   )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_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r5   rb   bq://bigqueryr5   bigquery_urizUnsupported source: )r   r   BatchJobSourcer#   )r   r   r   r   r   t_batch_job_source  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_destination  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)http_methodpathrequest_dicterrorz failed with error: z.
r.   )
r0   !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}|d u rtd|dr5|dd }td|}|d u r.td| |	d}|S |drA|dd }|S )NzFile name is required.zhttps://zfiles/r
   z	[a-z0-9]+z&Could not extract file name from URI: r   )
r>   r   rQ   r   r#   r   r$   r   r   group)r(   r   suffixr   r   r   r   t_file_name  s   


r  statusc                 C   s4   |dkrdS |dkrdS |dkrdS |dkrdS |S )	NSTATE_UNSPECIFIEDJOB_STATE_UNSPECIFIEDCREATINGJOB_STATE_RUNNINGACTIVEJOB_STATE_SUCCEEDEDFAILEDJOB_STATE_FAILEDr   )r(   r  r   r   r   t_tuning_job_status  s   r  r8   c                 C   s   t |ts|S t|dS )Nascii)r>   bytesbase64	b64encodedecode)r(   r8   r   r   r   t_bytes%  s   
r  )NNr   )T__doc__r  collections.abcr   r   r   r   r   r   r<   r   sysr   r   r   r   r   r	   TYPE_CHECKINGrM   rF   r    r   r   version_info	UnionTyper   r   _UnionGenericAlias	ApiClientrO   intr   r'   boolr-   rm   r\   Modelr1   r2   rD   rH   rP   PartDictPartTyperU   r]   re   rh   rl   ContentDictContentTypero   rt   ru   r   r   r   r   SchemaUnionDictr   SpeechConfigUnionDictr   r   r   r   r   r   r   r   r   r   r   r   r   r   rQ   r  JobStater  r  r  r   r   r   r   <module>   s  

]






=

 &

.



