forked from udacity/AIND-NLP-Bookworm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.py
83 lines (70 loc) · 2.8 KB
/
helper.py
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
"""Utility functions to support the notebook."""
import json
def fetch_credentials(service_name, creds_file="service-credentials.json"):
"""Fetch credentials for cloud services from file.
Params
======
- service_name: a Watson service name, e.g. "discovery" or "conversation"
- creds_file: file containing credentials in JSON format
Returns
=======
creds: dictionary containing credentials for specified service
"""
with open(creds_file, "r") as f:
creds = json.load(f)
return creds[service_name]
def fetch_object(service, obj_type, obj_name, create=False, create_args={}, **fetch_args):
"""Helper function to fetch objects from the Watson services.
Params
======
- service: a Watson service instance
- obj_type: object type, one of: "environment", "configuration", "collection", "workspace"
- obj_name: name used to look up / create object
- create: whether to create object if not found (default: False)
- create_args: arguments to pass in when creating, other than name
- fetch_args: other arguments used to fetch object, e.g. environment_id
Returns
=======
obj, obj_id: fetched object and its unique ID (for convenience)
"""
# Methods for each object type
list_methods = {
"environment": "get_environments",
"configuration": "list_configurations",
"collection": "list_collections",
"workspace": "list_workspaces"
}
get_methods = {
"environment": "get_environment",
"configuration": "get_configuration",
"collection": "get_collection",
"workspace": "get_workspace"
}
create_methods = {
"environment": "create_environment",
"configuration": "create_configuration",
"collection": "create_collection",
"workspace": "create_workspace"
}
# Look up by name
obj = None
obj_id = None
obj_list = service.__getattribute__(list_methods[obj_type])(**fetch_args)
for o in obj_list[obj_type + "s"]:
if o["name"] == obj_name:
obj = o
obj_id = obj[obj_type + "_id"]
print("Found {}: {} ({})".format(obj_type, obj_name, obj_id))
break
if obj_id: # fetch object
fetch_args[obj_type + "_id"] = obj_id
obj = service.__getattribute__(get_methods[obj_type])(**fetch_args)
elif create: # create new, if desired
if obj_type == "configuration": # handle configuration weirdness
create_args["config_data"]["name"] = obj_name
else:
create_args["name"] = obj_name
obj = service.__getattribute__(create_methods[obj_type])(**create_args)
obj_id = obj[obj_type + "_id"]
print("Created {}: {} ({})".format(obj_type, obj_name, obj_id))
return obj, obj_id