
    y1                        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mZ ddlm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 jobs API.    )absolute_import)division)unicode_literals)encoding)
list_pager)apis)	arg_utils)
exceptions)
properties)	resources)yamlc                       e Zd ZdZy)NoFieldsSpecifiedErrorzEError indicating that no updates were requested in a Patch operation.N__name__
__module____qualname____doc__     ,lib/googlecloudsdk/api_lib/ml_engine/jobs.pyr   r      s    Mr   r   c                       e Zd ZdZy)NoPackagesSpecifiedErrorz>Error that no packages were specified for non-custom training.Nr   r   r   r   r   r   #   s    Fr   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	 	 ddZd Zed        Zd Zed        Z	ed        Z
ed	        Zdd
Zd Zd Zd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)
JobsClientz3Client for jobs service in the Cloud ML Engine API.Nc                 x    |xs t        |      | _        |xs | j                  j                  | _        || _        y N)r    clientMESSAGES_MODULEmessages_short_message_prefix)selfr%   r'   short_message_prefixclient_versions        r   __init__zJobsClient.__init__2   s2    =-n=DK; ; ;DM!5Dr   c                 f    t        | j                  dj                  | j                  |      d       S )Nz{prefix}{name})prefixname)getattrr'   formatr(   )r)   short_message_names     r   GetShortMessagezJobsClient.GetShortMessage8   s9    4==#**$2L2L0B + DEIK Kr   c                 B    | j                   j                  j                  S r$   )r'   GoogleCloudMlV1JobStateValueValuesEnumr)   s    r   
state_enumzJobsClient.state_enum=   s    ==++@@@r   c                     | j                   j                  |j                               }t        j                  | j
                  j                  |dd      S )N)parentjobspageSize)fieldbatch_size_attribute)r'   MlProjectsJobsListRequestRelativeNamer   YieldFromListr%   projects_jobs)r)   project_refreqs      r   ListzJobsClient.ListA   sN    
--
1
1'') 2 +C##!!3f') )r   c                 .    | j                   j                  S r$   )r'   r5   r7   s    r   	job_classzJobsClient.job_classH   s    ==+++r   c                 .    | j                   j                  S r$   )r'   GoogleCloudMlV1TrainingInputr7   s    r   training_input_classzJobsClient.training_input_classL   s    ==555r   c                 .    | j                   j                  S r$   )r'   GoogleCloudMlV1PredictionInputr7   s    r   prediction_input_classz!JobsClient.prediction_input_classP   s    ==777r   c                 <    | j                   j                  ||      S )N)r:   googleCloudMlV1Job)r'   MlProjectsJobsCreateRequest)r)   r:   jobs      r   _MakeCreateRequestzJobsClient._MakeCreateRequestT   s$    ==44 5    r   c                     | j                   j                  j                  | j                  |j	                         |            S )N)r:   rQ   )r%   rB   CreaterR   r@   )r)   rC   rQ   s      r   rT   zJobsClient.CreateY   sA    ;;$$++++- 	  	 r   c                     | j                   j                  |j                               }| j                  j                  j                  |      S )zCancels given job.r/   )r'   MlProjectsJobsCancelRequestr@   r%   rB   Cancelr)   job_refrD   s      r   rX   zJobsClient.Cancel_   s=    
--
3
39M9M9O
3
PC;;$$++C00r   c                     | j                   j                  |j                               }| j                  j                  j                  |      S )NrV   )r'   MlProjectsJobsGetRequestr@   r%   rB   GetrY   s      r   r]   zJobsClient.Getd   s=    
--
0
0g6J6J6L
0
MC;;$$((--r   c                 \   | j                         }g }|j                  r"|j                  |_        |j                  d       |st	        d      | j
                  j                  |j                         |dj                  |            }| j                  j                  j                  |      S )zUpdate a job.labelszNo updates requested.,)r/   rO   
updateMask)rG   needs_updater_   appendr   r'   MlProjectsJobsPatchRequestr@   joinr%   rB   Patch)r)   rZ   labels_updaterQ   update_maskrD   s         r   rf   zJobsClient.Patchh   s    
..
CK!! ''cj""#:;;
--
2
2!!#88K( 3 C
 ;;$$**3//r   c                 p   | j                         }|r7t        j                  |      }|r t        j                  || j                         }|r||_        |||_        |j                  s| j                         |_        |||||||	|
|||d}|j                         D ]  \  }}|	t        |j                  ||       ! |rt        j                  |d|       |r0|j                         j                         D ]  \  }}|
|j                  d      r|j                  d      s|d   r)t        j                  |dj                  |      |d          |d   d   r,t        j                  |d	j                  |      |d   d          |d   d
   r,t        j                  |dj                  |      |d   d
          |dk(  s|d   st        j                  |dj                  |      |d          t        |j                  ||        | j!                  |      s| j#                  |      st%        d      |S )a~  Builds a Cloud ML Engine Job from a config file and/or flag values.

    Args:
        path: path to a yaml configuration file
        module_name: value to set for moduleName field (overrides yaml file)
        job_name: value to set for jobName field (overrides yaml file)
        trainer_uri: List of values to set for trainerUri field (overrides yaml
          file)
        region: compute region in which to run the job (overrides yaml file)
        job_dir: Cloud Storage working directory for the job (overrides yaml
          file)
        scale_tier: ScaleTierValueValuesEnum the scale tier for the job
          (overrides yaml file)
        user_args: [str]. A list of arguments to pass through to the job.
        (overrides yaml file)
        runtime_version: the runtime version in which to run the job (overrides
          yaml file)
        python_version: the Python version in which to run the job (overrides
          yaml file)
        network: user network to which the job should be peered with (overrides
          yaml file)
        service_account: A service account (email address string) to use for the
          job.
        labels: Job.LabelsValue, the Cloud labels for the job
        kms_key: A customer-managed encryption key to use for the job.
        custom_train_server_config: jobs_util.CustomTrainingInputServerConfig,
          configuration object for custom server parameters.
        enable_web_access: whether to enable the interactive shell for the job.
    Raises:
      NoPackagesSpecifiedError: if a non-custom job was specified without any
        trainer_uris.
    Returns:
        A constructed Job object.
    )pythonModuleargspackageUrisregionjobDir	scaleTierruntimeVersionpythonVersionnetworkserviceAccountenableWebAccessz)trainingInput.encryptionConfig.kmsKeyNameConfigTfConfigimageUriztrainingInput.{}.imageUriacceleratorConfigtypez'trainingInput.{}.acceleratorConfig.typecountz(trainingInput.{}.acceleratorConfig.countworkerConfigtpuTfVersionztrainingInput.{}.tpuTfVersionz#Non-custom jobs must have packages.)rG   r   	load_pathr   DictToMessagejobIdr_   trainingInputrJ   itemssetattrr	   SetFieldInMessageGetFieldMapendswithr1   HasPackageURIsIsCustomContainerTrainingr   )r)   pathmodule_namejob_nametrainer_urirm   job_dir
scale_tier	user_argsruntime_versionpython_versionrr   service_accountr_   kms_keycustom_train_server_configenable_web_accessrQ   dataadditional_fields
field_namevalues                         r   BuildTrainingJobzJobsClient.BuildTrainingJobx   sP   f ..
C ^^D!d	$$T4>>:cicj335c#")'), /446
E		!!:u5 7 !!#"M")+ "9EEGMMO
*e!!(+%%j1Z ))-44Z@
#% ()&1));BB:N+,V46 ()'2))<CCJO+,W57 ^+n0E))188D')
 C%%z593  P6 s#D,J,J3,O$%JKKJr   c                 @    t        |j                  j                        S r$   )boolr   rl   r)   rQ   s     r   r   zJobsClient.HasPackageURIs   s    !!--..r   c                     t        |j                  j                  xr  |j                  j                  j                        S r$   )r   r   masterConfigrw   r   s     r   r   z$JobsClient.IsCustomContainerTraining   s7    !!.. 8!!..779 9r   c           	      <   t         j                  j                  j                  j	                         }|r| j                  d      } |||      }nd}| j                  ||||	|
||      }|j                  |      |_        |r||_	        nv|r;t        j                  j                  |d||d      }|j                         |_        n9t        j                  j                  |dd	|i      }|j                         |_        |r||_        | j#                  |||
      S )av  Builds a Cloud ML Engine Job for batch prediction from flag values.

    Args:
        job_name: value to set for jobName field
        model_dir: str, Google Cloud Storage location of the model files
        model_name: str, value to set for modelName field
        version_name: str, value to set for versionName field
        input_paths: list of input files
        data_format: format of the input files
        output_path: single value for the output location
        region: compute region in which to run the job
        runtime_version: the runtime version in which to run the job
        max_worker_count: int, the maximum number of workers to use
        batch_size: int, the number of records per batch sent to Tensorflow
        signature_name: str, name of input/output signature in the TF meta graph
        labels: Job.LabelsValue, the Cloud labels for the job
        accelerator_count: int, The number of accelerators to attach to the
           machines
       accelerator_type: AcceleratorsValueListEntryValuesEnum, The type of
           accelerator to add to machine.
    Returns:
        A constructed Job object.
    AcceleratorConfig)rz   ry   N)
inputPaths
outputPathrm   rp   maxWorkerCount	batchSizeacceleratorzml.projects.models.versions)modelsId
projectsId)
collectionparamszml.projects.modelsr   )r   predictionInputr_   )r   VALUEScoreproject	GetOrFailr3   rM   DataFormatValueValuesEnum
dataFormaturir   REGISTRYParser@   versionName	modelNamesignatureNamerG   )r)   r   	model_dir
model_nameversion_nameinput_pathsdata_formatoutput_pathrm   r   max_worker_count
batch_sizesignature_namer_   accelerator_countaccelerator_type
project_idaccelerator_config_msgaccelerator_configprediction_inputversion_ref	model_refs                         r   BuildBatchPredictionJobz"JobsClient.BuildBatchPredictionJob   sM   N ""''//99;J#334GH18I7GI  22&'& 3  #3"L"L#&	&&,,
#@(
C - Ek &1%=%=%?"$$**
!5
+ + -i $-#9#9#; '5$>>(   r   )NNGoogleCloudMlV1v1)NN)NNNNNNNNNNNNNNNN)NNNNNNNNNNNNNNN)r   r   r   r   r,   r3   propertyr8   rE   rG   rJ   rM   rR   rT   rX   r]   rf   r   r   r   r   r   r   r   r"   r"   /   s    ;+/FJ6K
 A A) , , 6 6 8 8 
1
.0" !#' $#'"#"&!%'+&*#'+"#26)-!xt/9
 (,(,)-+/*.*.*.%).2/3)--1%)04/3Pr   r"   N)r   )r   F)r   
__future__r   r   r   apitools.base.pyr   r   googlecloudsdk.api_lib.utilr   $googlecloudsdk.command_lib.util.apisr	   googlecloudsdk.corer
   r   r   r   Errorr   r   r   r    objectr"   r   r   r   <module>r      sl    . &  ' % ' , : * * ) $NZ-- NGz// G/@Z Zr   