forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
107 lines (91 loc) · 3.1 KB
/
Copy pathpredict.py
File metadata and controls
107 lines (91 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Examples of using AI Platform's online prediction service."""
import argparse
import json
# [START import_libraries]
import googleapiclient.discovery
# [END import_libraries]
# [START predict_json]
# Create the AI Platform service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = googleapiclient.discovery.build('ml', 'v1')
def predict_json(project, model, instances, version=None):
"""Send json data to a deployed model for prediction.
Args:
project (str): project where the AI Platform Model is deployed.
model (str): model name.
instances ([Mapping[str: Any]]): Keys should be the names of Tensors
your deployed model expects as inputs. Values should be datatypes
convertible to Tensors, or (potentially nested) lists of datatypes
convertible to tensors.
version: str, version of the model to target.
Returns:
Mapping[str: any]: dictionary of prediction results defined by the
model.
"""
name = 'projects/{}/models/{}'.format(project, model)
if version is not None:
name += '/versions/{}'.format(version)
response = service.projects().predict(
name=name,
body={'instances': instances}
).execute()
if 'error' in response:
raise RuntimeError(response['error'])
return response['predictions']
# [END predict_json]
def main(project, model, version=None):
"""Send user input to the prediction service."""
while True:
try:
user_input = json.loads(input("Valid JSON >>>"))
except KeyboardInterrupt:
return
if not isinstance(user_input, list):
user_input = [user_input]
try:
result = predict_json(
project, model, user_input, version=version)
except RuntimeError as err:
print(str(err))
else:
print(result)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--project',
help='Project in which the model is deployed',
type=str,
required=True
)
parser.add_argument(
'--model',
help='Model name',
type=str,
required=True
)
parser.add_argument(
'--version',
help='Name of the version.',
type=str
)
args = parser.parse_args()
main(
args.project,
args.model,
version=args.version,
)