
                             d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ d
 Zd Z G d de      Zy)zUtilities for Edge ML API.    )absolute_import)division)unicode_literalsN)encoding_helper)
operations)util)
propertiesc                 4    t        j                  dd| d      S )z?Converts model[.tflite] style filename to model_edgetpu.tflite.z(\.tflite)?$z_edgetpu.tflite   countresubsources    +lib/googlecloudsdk/api_lib/edgeml/edgeml.py_CompileDestinationr      s    	!2F!	DD    c                 4    t        j                  dd| d      S )zGConverts model[/saved_model.(pb|pbtxt)] style filename to model.tflite.z(/saved_model\.(pb|pbtxt))?$z.tfliter   r   r   r   s    r   _ConvertDestinationr   "   s    	/F!	LLr   c                   .    e Zd ZdZddZd ZddZddZy)	EdgeMlClientzClient for Edge ML service.

  Attributes:
    client: Generated Edge ML API client.
    messages: Generated Edge ML API messages.
  Nc                     |xs t        j                         | _        |xs t        j                  |      | _        | j                  j
                  | _        t        j                  ||      | _	        y N)
r   GetClientInstanceclientGetMessagesModulemessagesprojects_models_servicer   OperationsClient_operations_client)selfr   r   s      r   __init__zEdgeMlClient.__init__/   sT    4D224DK> 6 6v >DMKK//DM(99&(KDr   c                    dt         j                  j                  j                  j	                         z   }| j
                  j                  | j
                  j                  | j
                  j                  |g            |      }| j                  j                  |      }| j                  j                  |      }t        j                  | j
                  j                  t        j                   |            }|S )a  Analyzes a machine learning model.

    The AnalyzeResponse will contain model's framework, and for TF models
    it will also contain Edge TPU compiliability and input/output tensor
    information.

    Args:
      source: str, GCS object URI to the model file or directory to analyze.

    Returns:
      AnalyzedResponse on the finish of analyze operation.

    Raises:
      LongrunningError: when long running operation fails.
    	projects/	inputUris	gcsSource)analyzeModelRequestproject)r	   VALUEScorer-   	GetOrFailr   "EdgemlProjectsModelsAnalyzeRequestAnalyzeModelRequest	GcsSourcer!   Analyzer#   WaitForOperationr   JsonToMessageAnalyzeModelResponseMessageToJson)r$   r   r-   analyze_req	operationresultresponses          r   r4   zEdgeMlClient.Analyze5   s      J--22::DDFFG--BB MM==mm---A > C C K %%k2I$$55i@F,,**%%f-/H Or   c                    dt         j                  j                  j                  j	                         z   }|st        |      }| j                  j                  }|j                  j                  }| j                  j                  | j                  j                  |g            }| j                  j                  | j                  j                  |            }| j                  j                   ||||      |      }| j                  j!                  |      }	| j"                  j%                  |	      }
t'        j(                  | j                  j*                  t'        j,                  |
            }||fS )a  Optimizes a TFLite model for EdgeTPU.

    Args:
      source: str, GCS object URI to the model file to compile. Must be a
        .tflite file.
      destination: str, GCS URI to an output tflite object. If not provided,
        for source filename `model[.tflite]` this will be set to
        `model_edgetpu.tflite`.

    Returns:
      (CompileModelResponse, output object URI) on the finish of compilation.

    Raises:
      LongrunningError: when long running operation fails.
    r'   r(   r*   	outputUrigcsDestination)chipTypeinputConfigoutputConfig)compileModelRequestr-   )r	   r.   r/   r-   r0   r   r   CompileModelRequestChipTypeValueValuesEnumEDGE_TPU_V1InputConfigr3   OutputConfigGcsDestination"EdgemlProjectsModelsCompileRequestr!   Compiler#   r5   r   r6   CompileModelResponser8   )r$   r   destinationr-   compile_req_type	chip_typeinput_configoutput_configcompile_reqr:   r;   r<   s               r   rM   zEdgeMlClient.CompileR   sL     J--22::DDFFG'/k}}88 88DDI==,,--))VH)= - ?LMM..}}33k3J / LM --BB,$&(  C K %%k2I$$55i@F,,**%%f-/H [  r   c                    dt         j                  j                  j                  j	                         z   }|st        |      }| j                  j                  | j                  j                  |g            }| j                  j                  | j                  j                  |            }| j                  j                  | j                  j                  ||      |      }| j                  j                  |      }| j                  j!                  |      }t#        j$                  | j                  j&                  t#        j(                  |            }	|	|fS )a  Converts Tensorflow SavedModel to TFLite model.

    Args:
      source: str, GCS URI to an input SavedModel archive
      destination: str, GCS URI to an output tflite object. If not provided,
        for source filename `model[/saved_model.(pb|pbtxt)]` this will be
        set to `model.tflite`.

    Returns:
      (ConvertModelResponse, output object URI) on the finish of
      convert operation.

    Raises:
      LongrunningError: when long running operation fails.
    r'   r(   r*   r>   r@   )rC   rD   )convertModelRequestr-   )r	   r.   r/   r-   r0   r   r   rI   r3   rJ   rK   "EdgemlProjectsModelsConvertRequestConvertModelRequestr!   Convertr#   r5   r   r6   ConvertModelResponser8   )
r$   r   rO   r-   rR   rS   convert_reqr:   r;   r<   s
             r   rY   zEdgeMlClient.Convert|   s5     J--22::DDFFG'/k==,,--))VH)= - ?LMM..}}33k3J / LM --BB MM==$= > B C K
 %%k2I$$55i@F,,**%%f-/H [  r   )NNr   )__name__
__module____qualname____doc__r%   r4   rM   rY    r   r   r   r   '   s    L:(!T$!r   r   )r_   
__future__r   r   r   r   apitools.base.pyr   googlecloudsdk.api_lib.edgemlr   r   googlecloudsdk.corer	   r   r   objectr   r`   r   r   <module>rf      s<    ! &  ' 	 , 4 . *E
M
y!6 y!r   