
    A                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ dd	l
mZ dd
lmZ ddlZ G d dej                         Z G d dej                         ZddZddZ G d de      Zy)z+Utilities for dealing with ML versions API.    )absolute_import)division)unicode_literals)encoding)
list_pager)apis)
exceptions)yaml)textNc                       e Zd ZdZy)InvalidVersionConfigFile7Error indicating an invalid Version configuration file.N__name__
__module____qualname____doc__     4lib/googlecloudsdk/api_lib/ml_engine/versions_api.pyr   r          ?r   r   c                       e Zd ZdZy)NoFieldsSpecifiedErrorr   Nr   r   r   r   r   r   "   r   r   r   c                 .    t        j                  d|       S )Nml)r   GetMessagesModule)versions    r   r   r   &   s    			g	..r   c                 2    t        j                  d| |      S )Nr   )no_http)r   GetClientInstance)r   r   s     r   r    r    *   s    			gw	??r   c                       e Zd ZdZ eg d      Z eddg      ZddZed        Z	d Z
d	 Zd
 Z	 	 	 	 	 ddZd Zd Zd Zd Zd Zd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)VersionsClientz3Client for the versions service of Cloud ML Engine.)autoScalingdeploymentUridescription	frameworklabelsmachineTypemanualScalingpackageUrispredictionClasspythonVersionruntimeVersionserviceAccount	containerroutesNc                 h    |xs
 t               | _        |xs | j                  j                  | _        y N)r    clientMESSAGES_MODULEmessages)selfr3   r5   s      r   __init__zVersionsClient.__init__E   s(    /-/DK; ; ;DMr   c                 .    | j                   j                  S r2   )r5   GoogleCloudMlV1Version)r6   s    r   version_classzVersionsClient.version_classI   s    ==///r   c                 <    | j                   j                  ||      S )N)parentgoogleCloudMlV1Version)r5   %MlProjectsModelsVersionsCreateRequest)r6   r<   r   s      r   _MakeCreateRequestz!VersionsClient._MakeCreateRequestM   s$    ==>>& ? ( (r   c                 p    | j                   j                         }| j                   j                  ||      S )N)name'googleCloudMlV1SetDefaultVersionRequest)r5   'GoogleCloudMlV1SetDefaultVersionRequest)MlProjectsModelsVersionsSetDefaultRequest)r6   rA   requests      r   _MakeSetDefaultRequestz%VersionsClient._MakeSetDefaultRequestR   s7    mmCCEG==BB07 C 9 9r   c                     | j                   j                  j                  | j                  |j	                         |            S )z+Creates a new version in an existing model.)r<   r   )r3   projects_models_versionsCreater?   RelativeName)r6   	model_refr   s      r   rI   zVersionsClient.CreateX   sA    ;;//66))+ 	  	 r   c                    | j                   j                         }g }|j                  r"|j                  |_        |j	                  d       |r||_        |j	                  d       |.|j                  r"|j	                  d       |j                  |_        ||j	                  d       ||_        |2|j	                  d       | j                   j                  |      |_
        |2|j	                  d       | j                   j                  |      |_        |P|j	                  d	       |j                  ||j                  _        n!| j                   j                  |
      |_        |
2|j	                  d       | j                   j                  |
      |_        |	Hd|vr3|j	                  d       | j                   j                  |	      |_        n|	|j                  _        |st#        d      | j$                  j&                  j)                  | j                   j+                  |j-                         |dj/                  t1        |                        S )zUpdate a version.r'   r%   r+   r*   zmanualScaling.nodes)nodeszautoScaling.minNodes)minNodeszautoScaling.maxNodes)maxNodesrequestLoggingConfig)bigqueryTableName)samplingPercentagezNo updates requested.,)rA   r=   
updateMask)r5   r9   needs_updater'   appendr%   valuer+   r*   GoogleCloudMlV1ManualScalingr)   GoogleCloudMlV1AutoScalingr#   rO   #GoogleCloudMlV1RequestLoggingConfigrP   rR   r   r3   rH   Patch$MlProjectsModelsVersionsPatchRequestrJ   joinsorted)r6   version_reflabels_updater%   prediction_class_updatepackage_urismanual_scaling_nodesauto_scaling_min_nodesauto_scaling_max_nodessampling_percentagebigquery_table_namer   update_masks                r   r[   zVersionsClient.Patch_   sG    mm224GK!!$++gn"'g'*/F/S/S*+ 7 = =g'(g'./"mmHH$ I &g )/0 MMDD) E +g )/0				('=$"mmFF+ G - &/0%)]]%V%V/ &W &1g" &	{	212'+}}'X'X2 (Y (4$ ;N$$7"#:;;;;//55::))+#*xx{ 34 	; 	67 7r   c                     | j                   j                  j                  | j                  j	                  |j                                     S )zDeletes a version from a model.rA   )r3   rH   Deleter5   %MlProjectsModelsVersionsDeleteRequestrJ   r6   r_   s     r   rk   zVersionsClient.Delete   sB    ;;//66;;))+ 	< 	-. .r   c                     | j                   j                  j                  | j                  j	                  |j                                     S )z-Gets details about an existing model version.rj   )r3   rH   Getr5   "MlProjectsModelsVersionsGetRequestrJ   rm   s     r   ro   zVersionsClient.Get   sB    ;;//3388))+ 	9 	-. .r   c                     | j                   j                  |j                               }t        j                  | j
                  j                  |dd      S )zLists the versions for a model.)r<   versionspageSize)fieldbatch_size_attribute)r5   #MlProjectsModelsVersionsListRequestrJ   r   YieldFromListr3   rH   )r6   rK   list_requests      r   ListzVersionsClient.List   sO    ==DD%%' E )L##,,lz; ;r   c                     | j                   j                  j                  | j                  |j	                                     S )zSets a model's default version.rj   )r3   rH   
SetDefaultrF   rJ   rm   s     r   r{   zVersionsClient.SetDefault   s;    ;;//::##)A)A)C#DF Fr   c                    	 t        j                  |      }|r t        j                  || j                        }t        j                         D cg c]$  }t        ||j                        r|j                  & c}      }||z
  t        |j                               z  }|rkt        dj	                  t!        j"                  t%        |      d      dj'                  t)        |            |dj'                  t)        |                        |S # t         j                  $ r>}t        dj	                  |t        j                  |j                                    d}~ww xY wc c}w )a  Read a config file and return Version object with the values.

    The object is based on a YAML configuration file. The file may only
    have the fields given in `allowed_fields`.

    Args:
      path: str, the path to the YAML file.
      allowed_fields: Collection, the fields allowed in the YAML.

    Returns:
      A Version object (for the corresponding API version).

    Raises:
      InvalidVersionConfigFile: If the file contains unexpected fields.
    z:Could not read Version configuration file [{path}]:

{err})patherrNzVInvalid {noun} [{fields}] in configuration file [{path}]. Allowed fields: [{allowed}].rt   , )nounfieldsr}   allowed)r
   	load_pathErrorr   formatsix	text_typeinner_errorr   DictToMessager:   set
all_fieldsgetattrrA   all_unrecognized_fieldsr   	Pluralizelenr]   r^   )	r6   r}   allowed_fieldsdatar~   r   fspecified_fieldsinvalid_fieldss	            r   
ReadConfigzVersionsClient.ReadConfig   sA    I^^D!d
 &&tT-?-?@gG,>,>,@ 6,@q#GQVV4 FF,@ 6 7&7'99;<=N$))/>>#n"5w?YYvn56ii~ 67	 *0 *9: : N' JJ I$&dcoo(F&GI II6s   D )E"E!9EEc           	      p   t        |j                               sy|d   sgdj                  t        |j	                               D cg c]  \  }}|s	dj                  |       c}}      }t        dj                  |            | j                  j                  |d         |_	        |d   r|d   |j                  _
        |d   r|d   |j                  _        |d	   rP|d	   j	                         D cg c]"  \  }}| j                  j                  ||
      $ c}}|j                  _        |d   r<|d   D cg c]  }| j                  j                  |        c}|j                  _        |d   s|d   r)| j                  j!                  |d   |d         |_        yyc c}}w c c}}w c c}w )z0Adds `container` and `routes` fields to version.Nimager   z--{}z--image was not provided, but other container related flags were specified. Please specify --image or remove the following flags: {})r   commandargsenv_vars)rA   rW   ports)containerPortpredict_routehealth_route)predicthealth)anyvaluesr]   r^   itemsr   
ValueErrorr5   GoogleCloudMlV1ContainerSpecr/   r   r   GoogleCloudMlV1EnvVarenvGoogleCloudMlV1ContainerPortr   GoogleCloudMlV1RouteMapr0   )	r6   r   kwargskv	set_flagsrA   rW   ps	            r   _ConfigureContainerz"VersionsClient._ConfigureContainer   s   v}}'?))(.v||~(>
D(>1!6==(>
DFivi " "
 BBWo C Gi"("3gf~%f~gj $J/55797kdE --
-
-4u
-
E79g g '?!"a --
4
41
4
E"!g
 o&"8}}<<)' = gn #9- E9!s   
F'
F'
8'F->#F3c                    t        |j                               sy| j                  j                         |_        |d   r|d   |j                  _        |d   r|d   |j                  _        |d   rg |j                  _        d|d   v ryt        |d   d         }|j                  j                  j                  | j                  j                  | j                  j                  j                  j                  |             d|d   v rzt        |d   d         }|j                  j                  j                  | j                  j                  | j                  j                  j                  j                  |             yyy)z&Adds `auto_scaling` fields to version.N	min_nodes	max_nodesmetricsz	cpu-usage)rA   targetzgpu-duty-cycle)r   r   r5   rY   r#   rN   rO   r   intrV   GoogleCloudMlV1MetricSpecNameValueValuesEnum	CPU_USAGEGPU_DUTY_CYCLE)r6   r   r   ts       r   _ConfigureAutoScalingz$VersionsClient._ConfigureAutoScaling  s[   v}}--BBDGk%+K%8g"k%+K%8g"i$&g!	y)	)y!+./##**MM33]]<<PP 4 	
 
VI.	.y!"234##**MM33]]<<PP 4 	 
/ r   c                    |r0| j                   }|s|| j                  z  }| j                  ||      }n| j                         }||||||||	|
|||d}d} |dk(  rC| j                  j                         } | j                  j                         }!||!_        |!| _        n|dk(  rC| j                  j                         } | j                  j                         }"||"_
        |"| _        nG|dk(  rB| j                  j                         } | j                  j                         }#||#_        |#| _        | | |d<   |s| j                  ||||||||       |s| j                  ||||       |j!                         D ]  \  }$}%|%	t#        ||$|%        |S )	a
  Create a Version object.

    The object is based on an optional YAML configuration file and the
    parameters to this method; any provided method parameters override any
    provided in-file configuration.

    The file may only have the fields given in
    VersionsClientBase._ALLOWED_YAML_FIELDS specified; the only parameters
    allowed are those that can be specified on the command line.

    Args:
      name: str, the name of the version object to create.
      path: str, the path to the YAML file.
      deployment_uri: str, the deploymentUri to set for the Version
      runtime_version: str, the runtimeVersion to set for the Version
      labels: Version.LabelsValue, the labels to set for the version
      machine_type: str, the machine type to serve the model version on.
      description: str, the version description.
      framework: FrameworkValueValuesEnum, the ML framework used to train this
        version of the model.
      python_version: str, The version of Python used to train the model.
      prediction_class: str, the FQN of a Python class implementing the Model
        interface for custom prediction.
      package_uris: list of str, Cloud Storage URIs containing user-supplied
        Python code to use.
      accelerator_config: an accelerator config message object.
      service_account: Specifies the service account for resource access
        control.
      explanation_method: Enables explanations and selects the explanation
        method. Valid options are 'integrated-gradients' and 'sampled-shapley'.
      num_integral_steps: Number of integral steps for Integrated Gradients and
        XRAI.
      num_paths: Number of paths for Sampled Shapley.
      image: The container image to deploy.
      command: Entrypoint for the container image.
      container_args: The command-line args to pass the container.
      env_vars: The environment variables to set on the container.
      ports: The ports to which traffic will be sent in the container.
      predict_route: The HTTP path within the container that predict requests
        are sent to.
      health_route: The HTTP path within the container that health checks are
        sent to.
      min_nodes: The minimum number of nodes to scale this model under load.
      max_nodes: The maximum number of nodes to scale this model under load.
      metrics: List of key-value pairs to set as metrics' target for
        autoscaling.
      containers_hidden: Whether or not container-related fields are hidden on
        this track.
      autoscaling_hidden: Whether or not autoscaling fields are hidden on this
        track.

    Returns:
      A Version object (for the corresponding API version).

    Raises:
      InvalidVersionConfigFile: If the file contains unexpected fields.
    )rA   r$   r-   r'   r(   r%   r&   r,   r+   r*   acceleratorConfigr.   Nzintegrated-gradientszsampled-shapleyxraiexplanationConfig)r   r   r   r   r   r   r   )r   r   r   )_ALLOWED_YAML_FIELDS_CONTAINER_FIELDSr   r:   r5    GoogleCloudMlV1ExplanationConfig-GoogleCloudMlV1IntegratedGradientsAttributionnumIntegralStepsintegratedGradientsAttribution(GoogleCloudMlV1SampledShapleyAttributionnumPathssampledShapleyAttributionGoogleCloudMlV1XraiAttributionxraiAttributionr   r   r   setattr)&r6   rA   r}   deployment_uriruntime_versionr'   machine_typer%   r&   python_versionprediction_classrb   accelerator_configservice_accountexplanation_methodnum_integral_steps	num_pathsr   r   container_argsr   r   r   r   r   r   r   containers_hiddenautoscaling_hiddenr   r   additional_fieldsexplanation_config	ig_configshap_configxrai_config
field_namerW   s&                                         r   BuildVersionzVersionsClient.BuildVersion  s   l 00n$000n5g""$g ')#"'+#/) 33==IIK--MMOi#5i :C7	0	0==IIKMMJJLk&k5@2	v	%==IIKMM@@Bk%7k"+6(%/A+,

%#  % 
  
Y)W ! N /446
E		U+ 7 Nr   )NN)NNNNNNNN)NNNNNNNNNNNNNNNNNNNNNNNNNTT)r   r   r   r   	frozensetr   r   r7   propertyr:   r?   rF   rI   r[   rk   ro   ry   r{   r   r   r   r   r   r   r   r"   r"   .   s    ;" $   ! 
< 0 0(
9 ;?7;>B=A $	>7@..;F
%N"H< "&#' $#!"&$( $&*#'&*&*!"& !% $!!%)&*9Tr   r"   )v1)r   F)r   
__future__r   r   r   apitools.base.pyr   r   googlecloudsdk.api_lib.utilr   googlecloudsdk.corer	   r
   googlecloudsdk.core.utilr   r   r   r   r   r   r    objectr"   r   r   r   <module>r      si    2 &  ' % ' , * $ ) 
@z// @@Z-- @/@EV Er   