|
| 1 | +# Copyright 2016 Google Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 4 | +# in compliance with the License. You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software distributed under the License |
| 9 | +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 10 | +# or implied. See the License for the specific language governing permissions and limitations under |
| 11 | +# the License. |
| 12 | + |
| 13 | +"""Implements Cloud ML Model Operations""" |
| 14 | + |
| 15 | +from googleapiclient import discovery |
| 16 | +import os |
| 17 | +import yaml |
| 18 | + |
| 19 | +import datalab.context |
| 20 | +import datalab.storage |
| 21 | +import datalab.utils |
| 22 | + |
| 23 | +from . import _util |
| 24 | + |
| 25 | +class Models(object): |
| 26 | + """Represents a list of Cloud ML models for a project.""" |
| 27 | + |
| 28 | + def __init__(self, project_id=None): |
| 29 | + """ |
| 30 | + Args: |
| 31 | + project_id: project_id of the models. If not provided, default project_id will be used. |
| 32 | + """ |
| 33 | + if project_id is None: |
| 34 | + project_id = datalab.context.Context.default().project_id |
| 35 | + self._project_id = project_id |
| 36 | + self._credentials = datalab.context.Context.default().credentials |
| 37 | + self._api = discovery.build('ml', 'v1', credentials=self._credentials) |
| 38 | + |
| 39 | + def _retrieve_models(self, page_token, page_size): |
| 40 | + list_info = self._api.projects().models().list( |
| 41 | + parent='projects/' + self._project_id, pageToken=page_token, pageSize=page_size).execute() |
| 42 | + models = list_info.get('models', []) |
| 43 | + page_token = list_info.get('nextPageToken', None) |
| 44 | + return models, page_token |
| 45 | + |
| 46 | + def get_iterator(self): |
| 47 | + """Get iterator of models so it can be used as "for model in Models().get_iterator()". |
| 48 | + """ |
| 49 | + return iter(datalab.utils.Iterator(self._retrieve_models)) |
| 50 | + |
| 51 | + def get_model_details(self, model_name): |
| 52 | + """Get details of the specified model from CloudML Service. |
| 53 | +
|
| 54 | + Args: |
| 55 | + model_name: the name of the model. It can be a model full name |
| 56 | + ("projects/[project_id]/models/[model_name]") or just [model_name]. |
| 57 | + Returns: a dictionary of the model details. |
| 58 | + """ |
| 59 | + full_name = model_name |
| 60 | + if not model_name.startswith('projects/'): |
| 61 | + full_name = ('projects/%s/models/%s' % (self._project_id, model_name)) |
| 62 | + return self._api.projects().models().get(name=full_name).execute() |
| 63 | + |
| 64 | + def create(self, model_name): |
| 65 | + """Create a model. |
| 66 | +
|
| 67 | + Args: |
| 68 | + model_name: the short name of the model, such as "iris". |
| 69 | + Returns: |
| 70 | + If successful, returns informaiton of the model, such as |
| 71 | + {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} |
| 72 | + Raises: |
| 73 | + If the model creation failed. |
| 74 | + """ |
| 75 | + body = {'name': model_name} |
| 76 | + parent = 'projects/' + self._project_id |
| 77 | + # Model creation is instant. If anything goes wrong, Exception will be thrown. |
| 78 | + return self._api.projects().models().create(body=body, parent=parent).execute() |
| 79 | + |
| 80 | + def delete(self, model_name): |
| 81 | + """Delete a model. |
| 82 | +
|
| 83 | + Args: |
| 84 | + model_name: the name of the model. It can be a model full name |
| 85 | + ("projects/[project_id]/models/[model_name]") or just [model_name]. |
| 86 | + """ |
| 87 | + full_name = model_name |
| 88 | + if not model_name.startswith('projects/'): |
| 89 | + full_name = ('projects/%s/models/%s' % (self._project_id, model_name)) |
| 90 | + response = self._api.projects().models().delete(name=full_name).execute() |
| 91 | + if 'name' not in response: |
| 92 | + raise Exception('Invalid response from service. "name" is not found.') |
| 93 | + _util.wait_for_long_running_operation(response['name']) |
| 94 | + |
| 95 | + def list(self, count=10): |
| 96 | + """List models under the current project in a table view. |
| 97 | +
|
| 98 | + Args: |
| 99 | + count: upper limit of the number of models to list. |
| 100 | + Raises: |
| 101 | + Exception if it is called in a non-IPython environment. |
| 102 | + """ |
| 103 | + import IPython |
| 104 | + data = [] |
| 105 | + # Add range(count) to loop so it will stop either it reaches count, or iteration |
| 106 | + # on self is exhausted. "self" is iterable (see __iter__() method). |
| 107 | + for _, model in zip(range(count), self): |
| 108 | + element = {'name': model['name']} |
| 109 | + if 'defaultVersion' in model: |
| 110 | + version_short_name = model['defaultVersion']['name'].split('/')[-1] |
| 111 | + element['defaultVersion'] = version_short_name |
| 112 | + data.append(element) |
| 113 | + |
| 114 | + IPython.display.display( |
| 115 | + datalab.utils.commands.render_dictionary(data, ['name', 'defaultVersion'])) |
| 116 | + |
| 117 | + def describe(self, model_name): |
| 118 | + """Print information of a specified model. |
| 119 | +
|
| 120 | + Args: |
| 121 | + model_name: the name of the model to print details on. |
| 122 | + """ |
| 123 | + model_yaml = yaml.safe_dump(self.get_model_details(model_name), default_flow_style=False) |
| 124 | + print model_yaml |
| 125 | + |
| 126 | + |
| 127 | +class ModelVersions(object): |
| 128 | + """Represents a list of versions for a Cloud ML model.""" |
| 129 | + |
| 130 | + def __init__(self, model_name, project_id=None): |
| 131 | + """ |
| 132 | + Args: |
| 133 | + model_name: the name of the model. It can be a model full name |
| 134 | + ("projects/[project_id]/models/[model_name]") or just [model_name]. |
| 135 | + project_id: project_id of the models. If not provided and model_name is not a full name |
| 136 | + (not including project_id), default project_id will be used. |
| 137 | + """ |
| 138 | + if project_id is None: |
| 139 | + self._project_id = datalab.context.Context.default().project_id |
| 140 | + self._credentials = datalab.context.Context.default().credentials |
| 141 | + self._api = discovery.build('ml', 'v1', credentials=self._credentials) |
| 142 | + if not model_name.startswith('projects/'): |
| 143 | + model_name = ('projects/%s/models/%s' % (self._project_id, model_name)) |
| 144 | + self._full_model_name = model_name |
| 145 | + self._model_name = self._full_model_name.split('/')[-1] |
| 146 | + |
| 147 | + def _retrieve_versions(self, page_token, page_size): |
| 148 | + parent = self._full_model_name |
| 149 | + list_info = self._api.projects().models().versions().list(parent=parent, |
| 150 | + pageToken=page_token, pageSize=page_size).execute() |
| 151 | + versions = list_info.get('versions', []) |
| 152 | + page_token = list_info.get('nextPageToken', None) |
| 153 | + return versions, page_token |
| 154 | + |
| 155 | + def get_iterator(self): |
| 156 | + """Get iterator of versions so it can be used as |
| 157 | + "for v in ModelVersions(model_name).get_iterator()". |
| 158 | + """ |
| 159 | + return iter(datalab.utils.Iterator(self._retrieve_versions)) |
| 160 | + |
| 161 | + def get_version_details(self, version_name): |
| 162 | + """Get details of a version. |
| 163 | +
|
| 164 | + Args: |
| 165 | + version: the name of the version in short form, such as "v1". |
| 166 | + Returns: a dictionary containing the version details. |
| 167 | + """ |
| 168 | + name = ('%s/versions/%s' % (self._full_model_name, version_name)) |
| 169 | + return self._api.projects().models().versions().get(name=name).execute() |
| 170 | + |
| 171 | + def deploy(self, version_name, path): |
| 172 | + """Deploy a model version to the cloud. |
| 173 | +
|
| 174 | + Args: |
| 175 | + version_name: the name of the version in short form, such as "v1". |
| 176 | + path: the Google Cloud Storage path (gs://...) which contains the model files. |
| 177 | +
|
| 178 | + Raises: Exception if the path is invalid or does not contain expected files. |
| 179 | + Exception if the service returns invalid response. |
| 180 | + """ |
| 181 | + if not path.startswith('gs://'): |
| 182 | + raise Exception('Invalid path. Only Google Cloud Storage path (gs://...) is accepted.') |
| 183 | + |
| 184 | + # If there is no "export.meta" or"saved_model.pb" under path but there is |
| 185 | + # path/model/export.meta or path/model/saved_model.pb, then append /model to the path. |
| 186 | + if (not datalab.storage.Item.from_url(os.path.join(path, 'export.meta')).exists() and |
| 187 | + not datalab.storage.Item.from_url(os.path.join(path, 'saved_model.pb')).exists()): |
| 188 | + if (datalab.storage.Item.from_url(os.path.join(path, 'model', 'export.meta')).exists() or |
| 189 | + datalab.storage.Item.from_url(os.path.join(path, 'model', 'saved_model.pb')).exists()): |
| 190 | + path = os.path.join(path, 'model') |
| 191 | + else: |
| 192 | + print('Cannot find export.meta or saved_model.pb, but continue with deployment anyway.') |
| 193 | + |
| 194 | + body = {'name': self._model_name} |
| 195 | + parent = 'projects/' + self._project_id |
| 196 | + try: |
| 197 | + self._api.projects().models().create(body=body, parent=parent).execute() |
| 198 | + except: |
| 199 | + # Trying to create an already existing model gets an error. Ignore it. |
| 200 | + pass |
| 201 | + body = { |
| 202 | + 'name': version_name, |
| 203 | + 'deployment_uri': path, |
| 204 | + 'runtime_version': '1.0', |
| 205 | + } |
| 206 | + response = self._api.projects().models().versions().create(body=body, |
| 207 | + parent=self._full_model_name).execute() |
| 208 | + if 'name' not in response: |
| 209 | + raise Exception('Invalid response from service. "name" is not found.') |
| 210 | + _util.wait_for_long_running_operation(response['name']) |
| 211 | + |
| 212 | + def delete(self, version_name): |
| 213 | + """Delete a version of model. |
| 214 | +
|
| 215 | + Args: |
| 216 | + version_name: the name of the version in short form, such as "v1". |
| 217 | + """ |
| 218 | + name = ('%s/versions/%s' % (self._full_model_name, version_name)) |
| 219 | + response = self._api.projects().models().versions().delete(name=name).execute() |
| 220 | + if 'name' not in response: |
| 221 | + raise Exception('Invalid response from service. "name" is not found.') |
| 222 | + _util.wait_for_long_running_operation(response['name']) |
| 223 | + |
| 224 | + def predict(self, version_name, data): |
| 225 | + """Get prediction results from features instances. |
| 226 | +
|
| 227 | + Args: |
| 228 | + version_name: the name of the version used for prediction. |
| 229 | + data: typically a list of instance to be submitted for prediction. The format of the |
| 230 | + instance depends on the model. For example, structured data model may require |
| 231 | + a csv line for each instance. |
| 232 | + Note that online prediction only works on models that take one placeholder value, |
| 233 | + such as a string encoding a csv line. |
| 234 | + Returns: |
| 235 | + A list of prediction results for given instances. Each element is a dictionary representing |
| 236 | + output mapping from the graph. |
| 237 | + An example: |
| 238 | + [{"predictions": 1, "score": [0.00078, 0.71406, 0.28515]}, |
| 239 | + {"predictions": 1, "score": [0.00244, 0.99634, 0.00121]}] |
| 240 | + """ |
| 241 | + full_version_name = ('%s/versions/%s' % (self._full_model_name, version_name)) |
| 242 | + request = self._api.projects().predict(body={'instances': data}, |
| 243 | + name=full_version_name) |
| 244 | + request.headers['user-agent'] = 'GoogleCloudDataLab/1.0' |
| 245 | + result = request.execute() |
| 246 | + if 'predictions' not in result: |
| 247 | + raise Exception('Invalid response from service. Cannot find "predictions" in response.') |
| 248 | + |
| 249 | + return result['predictions'] |
| 250 | + |
| 251 | + def describe(self, version_name): |
| 252 | + """Print information of a specified model. |
| 253 | +
|
| 254 | + Args: |
| 255 | + version: the name of the version in short form, such as "v1". |
| 256 | + """ |
| 257 | + version_yaml = yaml.safe_dump(self.get_version_details(version_name), |
| 258 | + default_flow_style=False) |
| 259 | + print version_yaml |
| 260 | + |
| 261 | + def list(self): |
| 262 | + """List versions under the current model in a table view. |
| 263 | +
|
| 264 | + Raises: |
| 265 | + Exception if it is called in a non-IPython environment. |
| 266 | + """ |
| 267 | + import IPython |
| 268 | + |
| 269 | + # "self" is iterable (see __iter__() method). |
| 270 | + data = [{'name': version['name'].split()[-1], |
| 271 | + 'deploymentUri': version['deploymentUri'], 'createTime': version['createTime']} |
| 272 | + for version in self] |
| 273 | + IPython.display.display( |
| 274 | + datalab.utils.commands.render_dictionary(data, ['name', 'deploymentUri', 'createTime'])) |
0 commit comments