
    (ph                     6   S r SSKrSSKrSSKrSSKrSSKJr  SSKrSSKrSSK	r	SSK	J
r
  SSK	Jr  SSK	Jr   SSK	Jr  Sr SSKrSrS
rSr\R*                  " S5      r\R*                  " S5      r\R*                  " S5      r\R*                  " S5      r\R*                  " S5      r\R*                  " S5      r\R*                  " S5      rS rS:S jrS:S jrS:S jr S:S jr!S:S jr"S;S jr#S:S jr$ " S S5      r% " S S5      r& " S S\&5      r' " S  S!5      r( " S" S#5      r) " S$ S%\(5      r* " S& S'\(5      r+ " S( S)5      r, " S* S+5      r-S, r.S:S- jr/S. r0S/ r1S0 r2S1 r3S2 r4S3 r5S4 r6S5 r7S6 r8S7 r9 " S8 S95      r:g! \ a    S	r GNHf = f! \ a    S	r GNPf = f)<zFirebase ML module.

This module contains functions for creating, updating, getting, listing,
deleting, publishing and unpublishing Firebase ML models.
    N)parse)_http_client)_utils)
exceptions)storageTF_mld   z^[A-Za-z0-9_-]{1,60}$z^[A-Za-z0-9_-]{1,32}$z;^gs://(?P<bucket_name>[a-z0-9_.-]{3,63})/(?P<blob_name>.+)$zm^projects/(?P<project_id>[a-z0-9-]{6,30})/locations/(?P<location_id>[^/]+)/models/(?P<model_id>[A-Za-z0-9]+)$zS^projects/(?P<project_id>[a-z0-9-]{6,30})/models/(?P<model_id>[A-Za-z0-9_-]{1,60})$z;^projects/(?P<project_id>[a-z0-9-]{6,30})/operations/[^/]+$c                 B    [         R                  " U [        [        5      $ )zReturns an _MLService instance for an App.

Args:
  app: A Firebase App instance (or None to use the default App).

Returns:
  _MLService: An _MLService for the specified App instance.

Raises:
  ValueError: If the app argument is invalid.
)r   get_app_service_ML_ATTRIBUTE
_MLServiceapps    D/var/www/html/venv/lib/python3.13/site-packages/firebase_admin/ml.py_get_ml_servicer   B   s     !!#}jAA    c                 ^    [        U5      n[        R                  UR                  U 5      US9$ )zCreates a model in the current Firebase project.

Args:
    model: An ml.Model to create.
    app: A Firebase app instance (or None to use the default app).

Returns:
    Model: The model that was created in Firebase ML.
r   )r   Model	from_dictcreate_modelmodelr   
ml_services      r   r   r   Q   ,     !%J??:2259s?CCr   c                 ^    [        U5      n[        R                  UR                  U 5      US9$ )zUpdates a model's metadata or model file.

Args:
    model: The ml.Model to update.
    app: A Firebase app instance (or None to use the default app).

Returns:
    Model: The updated model.
r   )r   r   r   update_modelr   s      r   r   r   _   r   r   c                 \    [        U5      n[        R                  UR                  U SS9US9$ )zPublishes a Firebase ML model.

A published model can be downloaded to client apps.

Args:
    model_id: The id of the model to publish.
    app: A Firebase app instance (or None to use the default app).

Returns:
    Model: The published model.
Tpublishr   r   r   r   set_publishedmodel_idr   r   s      r   publish_modelr$   m   s2     !%J??:33Hd3KQT?UUr   c                 \    [        U5      n[        R                  UR                  U SS9US9$ )zUnpublishes a Firebase ML model.

Args:
    model_id: The id of the model to unpublish.
    app: A Firebase app instance (or None to use the default app).

Returns:
    Model: The unpublished model.
Fr   r   r    r"   s      r   unpublish_modelr&   }   s2     !%J??:33He3LRU?VVr   c                 ^    [        U5      n[        R                  UR                  U 5      US9$ )zGets the model specified by the given ID.

Args:
    model_id: The id of the model to get.
    app: A Firebase app instance (or None to use the default app).

Returns:
 Model: The requested model.
r   )r   r   r   	get_modelr"   s      r   r(   r(      s,     !%J??://9s?CCr   c                 B    [        U5      n[        UR                  XX#S9$ )a  Lists the current project's models.

Args:
    list_filter: a list filter string such as ``tags:'tag_1'``. None will return all models.
    page_size: A number between 1 and 100 inclusive that specifies the maximum
        number of models to return per page. None for default.
    page_token: A next page token returned from a previous page of results. None
        for first page of results.
    app: A Firebase app instance (or None to use the default app).

Returns:
    ListModelsPage: A (filtered) list of models.
r   )r   ListModelsPagelist_models)list_filter	page_size
page_tokenr   r   s        r   r+   r+      s*     !%J
M Mr   c                 <    [        U5      nUR                  U 5        g)zDeletes a model from the current project.

Args:
    model_id: The id of the model you wish to delete.
    app: A Firebase app instance (or None to use the default app).
N)r   delete_modelr"   s      r   r0   r0      s     !%JH%r   c                      \ rS rSrSrSS jr\SS j5       rS rS r	S r
\S	 5       r\S
 5       r\R                  S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\R                  S 5       r\S 5       rSS jr\S 5       r\R                  S 5       rSS jrSrg)r      a5  A Firebase ML Model object.

Args:
    display_name: The display name of your model - used to identify your model in code.
    tags: Optional list of strings associated with your model. Can be used in list queries.
    model_format: A subclass of ModelFormat. (e.g. TFLiteFormat) Specifies the model details.
Nc                 f    S U l         0 U l        S U l        Ub  Xl        Ub  X l        Ub  X0l        g g N)_app_data_model_formatdisplay_nametagsmodel_format)selfr8   r9   r:   s       r   __init__Model.__init__   s@    	
!# ,I# , $r   c                     [        U5      nSnUR                  SS5      nUR                  SS5        U(       a  [        R                  U5      n[	        US9nX6l        X&l        U$ )-Create an instance of the object from a dict.NtfliteModel@typer:   )dictpopTFLiteFormatr   r   r6   r5   )clsdatar   	data_copytflite_formattflite_format_datar   s          r   r   Model.from_dict   s^     J	&]]=$?gt$(223EFM=1
r   c                 r    [         R                  U5      nUR                  U l        UR                  U l        g r4   )r   r   r:   r6   )r;   rG   copys      r   _update_from_dictModel._update_from_dict   s)    t$ --ZZ
r   c                     [        XR                  5      (       a9  U R                  UR                  :H  =(       a    U R                  UR                  :H  $ gNF)
isinstance	__class__r6   r7   r;   others     r   __eq__Model.__eq__   =    e^^,,::,Z1C1CuGZGZ1ZZr   c                 .    U R                  U5      (       + $ r4   rV   rT   s     r   __ne__Model.__ne__       ;;u%%%r   c                     U R                   R                  S5      (       d  g[        U R                   R                  S5      5      u  pU$ )z&The model's ID, unique to the project.nameN)r6   get_validate_and_parse_name)r;   _r#   s      r   r#   Model.model_id   s8     zz~~f%%.tzz~~f/EFr   c                 8    U R                   R                  S5      $ )zYThe model's display name, used to refer to the model in code and in
the Firebase console.displayNamer6   r`   r;   s    r   r8   Model.display_name   s     zz~~m,,r   c                 6    [        U5      U R                  S'   U $ )Nre   )_validate_display_namer6   )r;   r8   s     r   r8   rh      s    $:<$H

=!r   c                     U (       d  g Sn[         R                   R                  S5      n[         R                   R                  X5      n[        X2-
  R	                  5       S-  5      nU$ )Nz%Y-%m-%dT%H:%M:%S.%fZr   i  )datetimeutcfromtimestampstrptimeinttotal_seconds)date_string
format_strepochdatetime_objectmilliss        r   _convert_to_millisModel._convert_to_millis   sY    ,
!!2215"++44[Mo-<<>EFr   c                 `    [         R                  U R                  R                  SS5      5      $ )zThe time the model was created.
createTimeNr   rv   r6   r`   rg   s    r   create_timeModel.create_time  $     ''

|T(JKKr   c                 `    [         R                  U R                  R                  SS5      5      $ )z$The time the model was last updated.
updateTimeNrz   rg   s    r   update_timeModel.update_time	  r}   r   c                 x    U R                   R                  S0 5      R                  S0 5      R                  S5      $ )zValidation error message.statevalidationErrormessagerf   rg   s    r   validation_errorModel.validation_error  s2     zz~~gr*../@"EII)TTr   c                 j    [        U R                  R                  S0 5      R                  S5      5      $ )zETrue if the model is published and available for clients to
download.r   	published)boolr6   r`   rg   s    r   r   Model.published  s)     DJJNN7B/33K@AAr   c                 8    U R                   R                  S5      $ )z,The entity tag (ETag) of the model resource.etagrf   rg   s    r   r   
Model.etag       zz~~f%%r   c                 8    U R                   R                  S5      $ )z SHA256 hash of the model binary.	modelHashrf   rg   s    r   
model_hashModel.model_hash       zz~~k**r   c                 8    U R                   R                  S5      $ )z.Tag strings, used for filtering query results.r9   rf   rg   s    r   r9   
Model.tags#  r   r   c                 6    [        U5      U R                  S'   U $ )Nr9   )_validate_tagsr6   )r;   r9   s     r   r9   r   (  s    +D1

6r   c                     [        U R                  R                  S5      =(       a'    [        U R                  R                  S5      5      S:  5      $ )z:True if the Model object is locked by an active operation.activeOperationsr   )r   r6   r`   lenrg   s    r   lockedModel.locked-  sD     DJJNN#56 @

'9:;a?A 	Ar   c                    U R                   (       d  g[        U R                  5      nU R                  R	                  S5      S   R	                  S5      nUR                  UR                  U5      SUS9nU R                  U5        g)a!  Waits for the model to be unlocked. (All active operations complete)

Args:
    max_time_seconds: The maximum number of seconds to wait for the model to unlock.
        (None for no limit)

Raises:
    exceptions.DeadlineExceeded: If max_time_seconds passed and the model is still locked.
Nr   r   r_   T)wait_for_operationmax_time_seconds)r   r   r5   r6   r`   handle_operationget_operationrN   )r;   r   r   op_name
model_dicts        r   wait_for_unlockedModel.wait_for_unlocked3  sx     {{$TYY/
**..!34Q7;;FC00$$W-#- 1 /
 	z*r   c                     U R                   $ )z]The model's ``ModelFormat`` object, which represents the model's
format and storage location.)r7   rg   s    r   r:   Model.model_formatG  s     !!!r   c                 .    Ub  [        U5        Xl        U $ r4   )_validate_model_formatr7   )r;   r:   s     r   r:   r   M  s    #"<0)r   c                     [        U R                  5      nU R                  (       a(  UR                  U R                  R	                  US95        U$ )4Returns a serializable representation of the object.
for_upload)rC   r6   r7   updateas_dictr;   r   rM   s      r   r   Model.as_dictT  s>    DJJKK**22j2IJr   )r5   r6   r7   r8   r:   r9   )NNNr4   F)__name__
__module____qualname____firstlineno____doc__r<   classmethodr   rN   rV   r[   propertyr#   r8   setterstaticmethodrv   r{   r   r   r   r   r   r9   r   r   r:   r   __static_attributes__ r   r   r   r      s   
-   
&   - -
     L L L L U U B B
 & & + + & & 
[[  A A
+( " "
  r   r   c                   "    \ rS rSrSrSS jrSrg)ModelFormati\  z?Abstract base class representing a Model Format such as TFLite.c                     [         er   NotImplementedErrorr;   r   s     r   r   ModelFormat.as_dict^      !!r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   r   \  s
    I"r   r   c                       \ rS rSrSrSS jr\S 5       rS rS r	\
S 5       r\S	 5       r\R                  S
 5       r\S 5       rSS jrSrg)rE   ic  zModel format representing a TFLite model.

Args:
    model_source: A TFLiteModelSource sub class. Specifies the details of the model source.
Nc                 4    0 U l         S U l        Ub  Xl        g g r4   r6   _model_sourcemodel_sourcer;   r   s     r   r<   TFLiteFormat.__init__i  s"    
!# , $r   c                 X    [        U5      n[        U R                  U5      S9nX#l        U$ )r?   )r   )rC   rE   _init_model_sourcer6   )rF   rG   rH   rI   s       r   r   TFLiteFormat.from_dictp  s.     J	$#2H2H2ST'r   c                     [        XR                  5      (       a9  U R                  UR                  :H  =(       a    U R                  UR                  :H  $ grQ   )rR   rS   r6   r   rT   s     r   rV   TFLiteFormat.__eq__x  rX   r   c                 .    U R                  U5      (       + $ r4   rZ   rT   s     r   r[   TFLiteFormat.__ne__~  r]   r   c                     U R                  SS5      nU(       a	  [        US9$ U R                  SS5      nU(       a$  [        R                  " S[        5        [        US9$ g)zInitialize the ML model source.gcsTfliteUriN)gcs_tflite_uriautomlModelQAutoML model support is deprecated and will be removed in the next major version.)auto_ml_model)rD   TFLiteGCSModelSourcewarningswarnDeprecationWarningTFLiteAutoMlSource)rG   r   r   s      r   r   TFLiteFormat._init_model_source  sX     .$7'~FF5MM +,>@%MBBr   c                     U R                   $ )zThe TF Lite model's location.)r   rg   s    r   r   TFLiteFormat.model_source  s     !!!r   c                 V    Ub   [        U[        5      (       d  [        S5      eXl        g )Nz0Model source must be a TFLiteModelSource object.)rR   TFLiteModelSource	TypeErrorr   r   s     r   r   r     s(    #l,=>> RSS)r   c                 8    U R                   R                  S5      $ )z'The size in bytes of the TF Lite model.	sizeBytesrf   rg   s    r   
size_bytesTFLiteFormat.size_bytes  r   r   c                     [        U R                  5      nU R                  (       a(  UR                  U R                  R	                  US95        SU0$ )r   r   r@   )rC   r6   r   r   r   r   s      r   r   TFLiteFormat.as_dict  sD    DJJKK**22j2IJt$$r   r   r4   r   )r   r   r   r   r   r<   r   r   rV   r[   r   r   r   r   r   r   r   r   r   r   r   rE   rE   c  s    
-  & 
 
 " " * * + +%r   rE   c                   "    \ rS rSrSrSS jrSrg)r   i  zIAbstract base class representing a model source for TFLite format models.c                     [         er   r   r   s     r   r   TFLiteModelSource.as_dict  r   r   r   Nr   r   r   r   r   r   r     s
    S"r   r   c                   `    \ rS rSrSrSrSr\S 5       r\S 5       r	\S 5       r
\S 5       rS	rg
)_CloudStorageClienti  zCloud Storage helper classzgs://{0}/{1}zFirebase/ML/Models/{0}c                  0    [         (       d  [        S5      eg )NznFailed to import the Cloud Storage library for Python. Make sure to install the "google-cloud-storage" module.)_GCS_ENABLEDImportErrorr   r   r   _assert_gcs_enabled'_CloudStorageClient._assert_gcs_enabled  s!    | N O O r   c                     [         R                  U 5      nU(       d  [        S5      eUR                  S5      UR                  S5      4$ )N!GCS TFLite URI format is invalid.bucket_name	blob_name)_GCS_TFLITE_URI_PATTERNmatch
ValueErrorgroup)urimatchers     r   _parse_gcs_tflite_uri)_CloudStorageClient._parse_gcs_tflite_uri  s@     *//4@AA}}]+W]];-GGGr   c                 f   [         R                  5         [        R                  R	                  U5      n[
        R                  " XS9n[         R                  R                  U5      nUR                  U5      nUR                  U5        [         R                  R                  UR                  U5      $ )z4Upload a model file to the specified Storage bucket.r   )r   r   ospathbasenamer   bucket	BLOB_NAMEformatblobupload_from_filenameGCS_URIr_   )r   model_file_namer   	file_namer  r   r  s          r   upload_CloudStorageClient.upload  s     	//1GG$$_5	5'1188C	{{9%!!/2"**11&++yIIr   c                     [         R                  5         [         R                  U 5      u  p#[        R                  " X!S9nUR                  U5      nUR                  S[        R                  " SS9SS9$ )zHMakes the gcs_tflite_uri readable for GET for 10 minutes via signed_uri.r   v4
   )minutesGET)version
expirationmethod)	r   r   r  r   r  r  generate_signed_urlrl   	timedelta)r   r   r   r   r  r  s         r   sign_uri_CloudStorageClient.sign_uri  sk     	//1!4!J!J>!Z5{{9%''))"5 ( 
 	
r   r   N)r   r   r   r   r   r  r	  r   r   r  r  r  r   r   r   r   r   r     sc    $G(IO O
 H H 	J 	J 

 

r   r   c                       \ rS rSrSr\" 5       rSS jrS rS r	\
SS j5       r\S 5       r\S	 5       r\S
 5       r\
  SS j5       r\
  SS j5       r\S 5       r\R(                  S 5       rS rSS jrSrg)r   i  zCTFLite model source representing a tflite model file stored in GCS.Nc                 0    X l         [        U5      U l        g r4   )r5   _validate_gcs_tflite_uri_gcs_tflite_uri)r;   r   r   s      r   r<   TFLiteGCSModelSource.__init__  s    	7Gr   c                 j    [        XR                  5      (       a  U R                  UR                  :H  $ grQ   )rR   rS   r!  rT   s     r   rV   TFLiteGCSModelSource.__eq__  s+    e^^,,''5+@+@@@r   c                 .    U R                  U5      (       + $ r4   rZ   rT   s     r   r[   TFLiteGCSModelSource.__ne__  r]   r   c                 T    [         R                  R                  X!U5      n[        XCS9$ )a  Uploads the model file to an existing Google Cloud Storage bucket.

Args:
    model_file_name: The name of the model file.
    bucket_name: The name of an existing bucket. None to use the default bucket configured
        in the app.
    app: A Firebase app instance (or None to use the default app).

Returns:
    TFLiteGCSModelSource: The source created from the model_file

Raises:
    ImportError: If the Cloud Storage Library has not been installed.
)r   r   )r   _STORAGE_CLIENTr  )rF   r  r   r   gcs_uris        r   from_tflite_model_file+TFLiteGCSModelSource.from_tflite_model_file  s(      '66==k\_`#7DDr   c                  N   [         (       d  [        S5      e[        R                  R                  R                  S5      (       da  [        R                  R                  R                  S5      (       d2  [        SR                  [        R                  R                  5      5      eg g )Nz_Failed to import the tensorflow library for Python. Make sure to install the tensorflow module.1.z2.z5Expected tensorflow version 1.x or 2.x, but found {0})_TF_ENABLEDr   tfr  VERSION
startswithr
  r   r   r   _assert_tf_enabled'TFLiteGCSModelSource._assert_tf_enabled  s    { B C Czz!!,,T222::;M;M;X;XY];^;^U%vbjj&8&89; ; <_2r   c                 t    [         R                  R                  R                  U 5      nUR	                  5       $ r4   )r/  liteTFLiteConverterfrom_saved_modelconvert)saved_model_dir	converters     r   _tf_convert_from_saved_model1TFLiteGCSModelSource._tf_convert_from_saved_model
  s-     GG++<<_M	  ""r   c                    [         R                  R                  R                  S5      (       ad  Sn[         R                  R
                  R                  X5        [         R                  R                  R                  U5      nUR                  5       $ [         R                  R                  R                  U 5      nUR                  5       $ )z4Converts the given Keras model into a TF Lite model.r-  zfirebase_keras_model.h5)r/  r  r0  r1  kerasmodels
save_modelr5  r6  from_keras_model_filefrom_keras_modelr8  )keras_model
keras_filer:  s      r   _tf_convert_from_keras_model1TFLiteGCSModelSource._tf_convert_from_keras_model  s     ::((..2JHHOO&&{?//EEjQI   "" //@@MI  ""r   c                     [         R                  5         [         R                  U5      n[        US5       nUR	                  U5        SSS5        [         R                  X#U5      $ ! , (       d  f       N$= f)aO  Creates a Tensor Flow Lite model from the saved model, and uploads the model to GCS.

Args:
    saved_model_dir: The saved model directory.
    model_file_name: The name that the tflite model will be saved as in Cloud Storage.
    bucket_name: The name of an existing bucket. None to use the default bucket configured
        in the app.
    app: Optional. A Firebase app instance (or None to use the default app)

Returns:
    TFLiteGCSModelSource: The source created from the saved_model_dir

Raises:
    ImportError: If the Tensor Flow or Cloud Storage Libraries have not been installed.
wbN)r   r2  r;  openwriter*  )rF   r9  r  r   r   tflite_model
model_files          r   r7  %TFLiteGCSModelSource.from_saved_model  s\    $ 	//1+HHY/4(J\* )#::?Y\]] )(   A&&
A4c                     [         R                  5         [         R                  U5      n[        US5       nUR	                  U5        SSS5        [         R                  X#U5      $ ! , (       d  f       N$= f)a>  Creates a Tensor Flow Lite model from the keras model, and uploads the model to GCS.

Args:
    keras_model: A tf.keras model.
    model_file_name: The name that the tflite model will be saved as in Cloud Storage.
    bucket_name: The name of an existing bucket. None to use the default bucket configured
        in the app.
    app: Optional. A Firebase app instance (or None to use the default app)

Returns:
    TFLiteGCSModelSource: The source created from the keras_model

Raises:
    ImportError: If the Tensor Flow or Cloud Storage Libraries have not been installed.
rH  N)r   r2  rE  rI  rJ  r*  )rF   rC  r  r   r   rK  rL  s          r   rB  %TFLiteGCSModelSource.from_keras_model5  s\    $ 	//1+HHU/4(J\* )#::?Y\]] )(rN  c                     U R                   $ )z'URI of the model file in Cloud Storage.)r!  rg   s    r   r   #TFLiteGCSModelSource.gcs_tflite_uriM  s     ###r   c                 $    [        U5      U l        g r4   )r   r!  )r;   r   s     r   r   rR  R  s    7Gr   c                 j    [         R                  R                  U R                  U R                  5      $ )zQSigns the GCS uri, so the model file can be uploaded to Firebase ML and verified.)r   r(  r  r!  r5   rg   s    r   _get_signed_gcs_tflite_uri/TFLiteGCSModelSource._get_signed_gcs_tflite_uriV  s(    #33<<T=Q=QSWS\S\]]r   c                 P    U(       a  SU R                  5       0$ SU R                  0$ )r   r   )rU  r!  r   s     r   r   TFLiteGCSModelSource.as_dictZ  s*    "D$C$C$EFF 4 455r   )r5   r!  r4   )NN)zfirebase_ml_model.tfliteNNr   )r   r   r   r   r   r   r(  r<   rV   r[   r   r*  r   r2  r;  rE  r7  rB  r   r   r   rU  r   r   r   r   r   r   r     s    M)+OH
& E E$ ; ; # #
 
# 
# ?Y/3^ ^. ;U/3^ ^. $ $ H H^6r   r   c                   l    \ rS rSrSrSS jrS rS r\S 5       r	\	R                  S 5       r	SS	 jrS
rg)r   ib  zTFLite model source representing a tflite model created with AutoML.

AutoML model support is deprecated and will be removed in the next major version.
Nc                 R    [         R                  " S[        5        X l        Xl        g )Nr   )r   r   r   r5   r   )r;   r   r   s      r   r<   TFLiteAutoMlSource.__init__h  s!     '(:	<	*r   c                 j    [        XR                  5      (       a  U R                  UR                  :H  $ grQ   )rR   rS   r   rT   s     r   rV   TFLiteAutoMlSource.__eq__n  s+    e^^,,%%)<)<<<r   c                 .    U R                  U5      (       + $ r4   rZ   rT   s     r   r[   TFLiteAutoMlSource.__ne__s  r]   r   c                     U R                   $ )zGResource name of the model, created by the AutoML API or Cloud console._auto_ml_modelrg   s    r   r    TFLiteAutoMlSource.auto_ml_modelv  s     """r   c                 $    [        U5      U l        g r4   )_validate_auto_ml_modelrb  )r;   r   s     r   r   rc  {  s    5mDr   c                     SU R                   0$ )r   r   ra  r   s     r   r   TFLiteAutoMlSource.as_dict  s     t2233r   )r5   rb  r   r4   r   )r   r   r   r   r   r<   rV   r[   r   r   r   r   r   r   r   r   r   r   b  sK    
+
& # # E E4r   r   c                   j    \ rS rSrSrS r\S 5       r\S 5       r\S 5       r	\S 5       r
S rS	 rS
rg)r*   i  a2  Represents a page of models in a Firebase project.

Provides methods for traversing the models included in this page, as well as
retrieving subsequent pages of models. The iterator returned by
``iterate_all()`` can be used to iterate through all the models in the
Firebase project starting from this page.
c                 \    Xl         X l        X0l        X@l        XPl        U" X#U5      U l        g r4   )_list_models_func_list_filter
_page_size_page_tokenr5   _list_response)r;   list_models_funcr,   r-   r.   r   s         r   r<   ListModelsPage.__init__  s-    !1'#%	.{zRr   c                     U R                   R                  S/ 5       Vs/ s H   n[        R                  XR                  S9PM"     sn$ s  snf )z A list of Models from this page.r?  r   )rn  r`   r   r   r5   )r;   r   s     r   r?  ListModelsPage.models  sL     @D?R?R?V?VW_ac?d
?deEOOEyyO1?d
 	
 
s   'A	c                     U R                   $ )z,The filter string used to filter the models.)rk  rg   s    r   r,   ListModelsPage.list_filter  s        r   c                 :    U R                   R                  SS5      $ )z+Token identifying the next page of results.nextPageToken )rn  r`   rg   s    r   next_page_tokenListModelsPage.next_page_token  s     ""&&;;r   c                 ,    [        U R                  5      $ )z!True if more pages are available.)r   rx  rg   s    r   has_next_pageListModelsPage.has_next_page  s     D(())r   c                     U R                   (       aA  [        U R                  U R                  U R                  U R
                  U R                  5      $ g)zRetrieves the next page of models if available.

Returns:
    ListModelsPage: Next page of models, or None if this is the last page.
N)r{  r*   rj  rk  rl  rx  r5   rg   s    r   get_next_pageListModelsPage.get_next_page  sH     !&&!!$$		  r   c                     [        U 5      $ )a  Retrieves an iterator for Models.

Returned iterator will iterate through all the models in the Firebase
project starting from this page. The iterator will never buffer more than
one page of models in memory at a time.

Returns:
    iterator: An iterator of Model instances.
)_ModelIteratorrg   s    r   iterate_allListModelsPage.iterate_all  s     d##r   )r5   rk  rj  rn  rl  rm  N)r   r   r   r   r   r<   r   r?  r,   rx  r{  r~  r  r   r   r   r   r*   r*     sg    S 
 
 ! ! < < * *
$r   r*   c                   0    \ rS rSrSrS rS rS rS rSr	g)	r  i  a  An iterator that allows iterating over models, one at a time.

This implementation loads a page of models into memory, and iterates on them.
When the whole page has been traversed, it loads another page. This class
never keeps more than one page of entries in memory.
c                 ^    [        U[        5      (       d  [        S5      eXl        SU l        g )Nz%Current page must be a ListModelsPager   )rR   r*   r   _current_page_index)r;   current_pages     r   r<   _ModelIterator.__init__  s(    ,77CDD)r   c                    U R                   [        U R                  R                  5      :X  aA  U R                  R                  (       a&  U R                  R                  5       U l        SU l         U R                   [        U R                  R                  5      :  a:  U R                  R                  U R                      nU =R                   S-  sl         U$ [        e)Nr      )r  r   r  r?  r{  r~  StopIteration)r;   results     r   next_ModelIterator.next  s    ;;#d007788!!//%)%7%7%E%E%G";;T//6677''..t{{;FKK1KMr   c                 "    U R                  5       $ r4   )r  rg   s    r   __next___ModelIterator.__next__  s    yy{r   c                     U $ r4   r   rg   s    r   __iter___ModelIterator.__iter__  s    r   )r  r  N)
r   r   r   r   r   r<   r  r  r  r   r   r   r   r  r    s    	r   r  c                     [         R                  U 5      nU(       d  [        S5      eUR                  S5      UR                  S5      4$ )N&Model resource name format is invalid.
project_idr#   )_RESOURCE_NAME_PATTERNr   r   r   )r_   r  s     r   ra   ra     s@     %**40GABB==&j(AAAr   c                     [        U [        5      (       d  [        S5      eUc  U R                  (       d  [	        S5      eg g )NzModel must be an ml.Model.zModel must have a display name.)rR   r   r   r8   r   )r   update_masks     r   _validate_modelr    s=    eU##4555#5#5:;; $6r   c                 N    [         R                  U 5      (       d  [        S5      eg )NzModel ID format is invalid.)_MODEL_ID_PATTERNr   r   )r#   s    r   _validate_model_idr    s$    ""8,,677 -r   c                 P    [         R                  U 5      (       d  [        S5      eU $ )Nz!Operation name format is invalid.)_OPERATION_NAME_PATTERNr   r   )r   s    r   _validate_operation_namer    s$    "((11<==Nr   c                 P    [         R                  U 5      (       d  [        S5      eU $ )NzDisplay name format is invalid.)_DISPLAY_NAME_PATTERNr   r   )r8   s    r   rj   rj     s%     &&|44:;;r   c                     [        U [        5      (       a  [        S U  5       5      (       d  [        S5      e[        S U  5       5      (       d  [	        S5      eU $ )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7fr4   )rR   str.0tags     r   	<genexpr>!_validate_tags.<locals>.<genexpr>
  s     1DSJsC  Ds   zTags must be a list of strings.c              3   L   #    U  H  n[         R                  U5      v   M     g 7fr4   )_TAG_PATTERNr   r  s     r   r  r    s     7$3|!!#&&$s   "$zTag format is invalid.)rR   listallr   r   )r9   s    r   r   r     sN    dD!!1D1119::7$777122Kr   c                 P    [         R                  U 5      (       d  [        S5      eU $ )Nr   )r   r   r   )r   s    r   r   r     s&     #((--<==Jr   c                 P    [         R                  U 5      (       d  [        S5      eU $ )Nr  )_AUTO_ML_MODEL_PATTERNr   r   )r   s    r   re  re    s$    !''..ABBLr   c                 F    [        U [        5      (       d  [        S5      eU $ )Nz*Model format must be a ModelFormat object.)rR   r   r   rB   s    r   r   r     s!    lK00DEEr   c                 L    U b!  [        U [        5      (       d  [        S5      eg g )Nz%List filter must be a string or None.rR   r  r   )r,   s    r   _validate_list_filterr  $  s+    +s++CDD , r   c                     U bL  [        U 5      [        La  [        S5      eU S:  d
  U [        :  a  [	        SR                  [        5      5      eg g )Nz#Page size must be a number or None.r  z6Page size must be a positive integer between 1 and {0})typero   r   _MAX_PAGE_SIZEr   r
  )r-   s    r   _validate_page_sizer  *  sV    	?#%ABBq=I6 ))/)?A A 7	 r   c                 L    U b!  [        U [        5      (       d  [        S5      eg g )Nz$Page token must be a string or None.r  )r.   s    r   _validate_page_tokenr  4  s+    *c**BCC + r   c                   l    \ rS rSrSrSrSrSrSrS r	S r
S	 rSS jrS rSS jrS rS rS rS rSrg
)r   i:  zFirebase ML service.z7https://firebaseml.googleapis.com/v1beta2/projects/{0}/z*https://firebaseml.googleapis.com/v1beta2/g      ?   c                    UR                   U l        U R                  (       d  [        S5      e[        R                  R                  U R                  5      U l        SSR                  [        R                  5      0n[        R                  " UR                  R                  5       UU R                  S9U l        [        R                  " UR                  R                  5       U[        R                  S9U l        g )NzqProject ID is required to access ML service. Either set the projectId option, or use service account credentials.zX-FIREBASE-CLIENTzfire-admin-python/{0})
credentialheadersbase_url)r  _project_idr   r   PROJECT_URLr
  _project_urlfirebase_admin__version__r   JsonHttpClientr  get_credential_clientOPERATION_URL_operation_client)r;   r   
ml_headerss      r   r<   _MLService.__init__B  s    >>HI I '2299$:J:JK!8!?!?@Z@Z![

 $22~~446&&( ".!<!<~~446--"/r   c                     [        U5         U R                  R                  SUS9$ ! [        R                  R
                   a  n[        R                  " U5      eS nAff = f)Nr`   url)r  r  bodyrequestsr   RequestExceptionr   #handle_platform_error_from_requests)r;   r   errors      r   r   _MLService.get_operationU  s[     )	D))..u'.BB""33 	D<<UCC	Ds   ' A AA c                 B   [        [        R                  U5      nU[        R                  -  nUbY  U[        R                  R                  5       -
  R                  5       nUS:  a  [        R                  " S5      e[        XES-
  5      n[        R                  " U5        g)zGSleeps for the appropriate amount of time. Or throws deadline exceeded.Nr  zPolling max time exceeded.)powr   POLL_EXPONENTIAL_BACKOFF_FACTORPOLL_BASE_WAIT_TIME_SECONDSrl   nowrp   r   DeadlineExceededErrormintimesleep)r;   current_attempt	stop_timedelay_factorwait_time_secondsmax_seconds_lefts         r   _exponential_backoff_MLService._exponential_backoff\  s    :EEW(:+Q+QQ  )H,=,=,A,A,C CRRT!# 667STT #$5!7K L

$%r   Nc                    [        U[        5      (       d  [        S5      eUR                  S5      (       av  UR                  S5      (       a  UR                  S5      $ UR                  S5      (       a%  [        R
                  " UR                  S5      5      e[        R                  " SS9e[        UR                  S5      5      nUR                  S0 5      nUR                  S	S
5      nUR                  S5      (       d  [        S5      e[        UR                  S5      5      u  pxSn	[        R                  R                  5       n
Uc  SOU
[        R                  " US9-   nU(       a\  UR                  S5      (       dF  U R                  X5        U R                  U5      nU	S-  n	U(       a  UR                  S5      (       d  MF  UR                  S5      (       ab  UR                  S5      (       a  UR                  S5      $ UR                  S5      (       a%  [        R
                  " UR                  S5      5      e[!        U5      R#                  5       $ )a  Handles long running operations.

Args:
    operation: The operation to handle.
    wait_for_operation: Should we allow polling for the operation to complete.
        If no polling is requested, a locked model will be returned instead.
    max_time_seconds: The maximum seconds to try polling for operation complete.
        (None for no limit)

Returns:
    dict: A dictionary of the returned model properties.

Raises:
    TypeError: if the operation is not a dictionary.
    ValueError: If the operation is malformed.
    UnknownError: If the server responds with an unexpected response.
    err: If the operation exceeds polling attempts or stop_time
zOperation must be a dictionary.doneresponser  z$Internal Error: Malformed Operation.)r   r_   metadatarA   rw  ModelOperationMetadataz#Unknown type of operation metadata.r   N)secondsr  )rR   rC   r   r`   r   handle_operation_errorr   UnknownErrorr  endswithra   rl   r  r  r  r   r(   r   )r;   	operationr   r   r   r  metadata_typerb   r#   r  
start_timer  s               r   r   _MLService.handle_operationh  s   & )T**=>>==  }}Z(( }}Z00}}W%%33IMM'4JKK))2XYY*9==+@A==R0 Wb1%%&>??ABB.x||F/CD&&**,
-5T("4"4=M"NN 	 v)>)> %%oA**73Iq O !v)>)> ==  }}Z(( }}Z00}}W%%33IMM'4JKK "**,,r   c           
          [        U5         U R                  U R                  R                  SSUR	                  SS9S95      $ ! [
        R                  R                   a  n[        R                  " U5      eS nAff = f)Npostr?  Tr   r  json)
r  r   r  r  r   r  r   r  r   r  )r;   r   r  s      r   r   _MLService.create_model  sy    	D((!!&hU]]VZ]=[!\^ ^""33 	D<<UCC	Ds   6A A="A88A=c           
      b   [        X5        SR                  UR                  5      nUb  USR                  U5      -   n U R                  U R                  R                  SX1R                  SS9S95      $ ! [        R                  R                   a  n[        R                  " U5      eS nAff = f)N
models/{0}z?updateMask={0}patchTr   r  )r  r
  r#   r   r  r  r   r  r   r  r   r  )r;   r   r  r  r  s        r   r   _MLService.update_model  s    +""5>>2"+22;??D	D((!!'t--SW-:X!Y[ [""33 	D<<UCC	Ds   5A5 5B.B))B.c                     [        U5        SR                  U R                  U5      n[        R	                  USU0S.5      nU R                  USS9$ )Nzprojects/{0}/models/{1}r   )r_   r   zstate.published)r  )r  r
  r  r   r   r   )r;   r#   r   
model_namer   s        r   r!   _MLService.set_published  s[    8$.55d6F6FQ
W!
    4E FFr   c                     [        U5         U R                  R                  SSR                  U5      S9$ ! [        R
                  R                   a  n[        R                  " U5      eS nAff = f)Nr`   r  r  	r  r  r  r
  r  r   r  r   r  r;   r#   r  s      r   r(   _MLService.get_model  sd    8$	D<<$$U0C0CH0M$NN""33 	D<<UCC	Ds   (6 A/A**A/c                    [        U5        [        U5        [        U5        0 nU(       a  XS'   U(       a  X$S'   U(       a  X4S'   SnU(       a6  [        R                  " [        UR                  5       5      S5      nUS-   U-   n U R                  R                  SUS9$ ! [        R                  R                   a  n[        R                  " U5      eS	nAff = f)
zlists Firebase ML models.filterr-   r.   r?  T?r`   r  N)r  r  r  r   	urlencodesorteditemsr  r  r  r   r  r   r  )r;   r,   r-   r.   paramsr  	param_strr  s           r   r+   _MLService.list_models  s    k*I&Z(*8"+;#-< v||~(>EI#:	)D	D<<$$U$55""33 	D<<UCC	Ds   B C=CCc                     [        U5         U R                  R                  SSR                  U5      S9  g ! [        R
                  R                   a  n[        R                  " U5      eS nAff = f)Ndeleter  r  r  r  s      r   r0   _MLService.delete_model  sa    8$	DLLhL,?,?,IJ""33 	D<<UCC	Ds   )7 A0A++A0)r  r  r  r  )FNr4   )r   r   r   r   r   r  r  r  r  r<   r   r  r   r   r   r!   r(   r+   r0   r   r   r   r   r   r   :  sU    KK@M&)#"#/&D
&6-rD	D	GDD*Dr   r   r4   )NNNN);r   rl   rer  r  urllibr   r   r  r  r   r   r   r   r   r   
tensorflowr/  r.  r   r  compiler  r  r  r   r  r  r  r   r   r   r$   r&   r(   r+   r0   r   r   rE   r   r   r   r   r*   r  ra   r  r  r  rj   r   r   re  r   r  r  r  r   r   r   r   <module>r     s    	  	     ' ! %&L
K JJ78 

#;< zz23**BD *+  Z\ **BD BDDV WDM&&b bJ" "A%; A%H" ",
 ,
^B6, B6J 4*  4F?$ ?$D >B<8
EADfD fDe  L  Ks#   E= F =F	F	FF