-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdata.py
342 lines (275 loc) · 11 KB
/
data.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import click
import sys
import os
import os.path
from tabulate import tabulate
import webbrowser
import floyd
from floyd.client.experiment import ExperimentClient
from floyd.client.data import DataClient
from floyd.client.dataset import DatasetClient
from floyd.exceptions import FloydException
from floyd.manager.auth_config import AuthConfigManager
from floyd.manager.data_config import DataConfig, DataConfigManager
from floyd.log import logger as floyd_logger
from floyd.cli.data_upload_utils import (
opt_to_resume, upload_is_resumable, abort_previous_upload,
initialize_new_upload, complete_upload
)
from floyd.cli.utils import (
normalize_data_name,
normalize_job_name,
get_namespace_from_name
)
@click.group()
def data():
"""
Subcommand for data operations.
"""
pass
@click.command()
@click.argument('dataset-name', nargs=1)
def init(dataset_name):
"""
Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload
"""
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get_namespace_from_name(dataset_name)
create_dataset_base_url = "{}/datasets/create".format(floyd.floyd_web_host)
create_dataset_url = "{}?name={}&namespace={}".format(create_dataset_base_url, name, namespace)
floyd_logger.info(("Dataset name does not match your list of datasets. "
"Create your new dataset in the web dashboard:\n\t%s"),
create_dataset_base_url)
webbrowser.open(create_dataset_url)
name = click.prompt('Press ENTER to use dataset name "%s" or enter a different name' % dataset_name, default=dataset_name, show_default=False)
dataset_name = name.strip() or dataset_name
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
raise FloydException('Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name)
namespace, name = get_namespace_from_name(dataset_name)
data_config = DataConfig(name=name,
namespace=namespace,
family_id=dataset_obj.id)
DataConfigManager.set_config(data_config)
floyd_logger.info("Data source \"{}\" initialized in current directory".format(dataset_name))
floyd_logger.info("""
You can now upload your data to Floyd by:
floyd data upload
""")
@click.command()
@click.option('-r', '--resume',
is_flag=True, default=False, help='Resume previous upload')
@click.option('--message', '-m', default='',
help='Job commit message')
def upload(resume, message):
"""
Upload files in the current dir to FloydHub.
"""
data_config = DataConfigManager.get_config()
if not upload_is_resumable(data_config) or not opt_to_resume(resume):
abort_previous_upload(data_config)
access_token = AuthConfigManager.get_access_token()
initialize_new_upload(data_config, access_token, message)
complete_upload(data_config)
@click.command()
@click.argument('id', required=False, nargs=1)
def status(id):
"""
View status of all versions in a dataset.
The command also accepts a specific dataset version.
"""
if id:
data_source = get_data_object(id, use_data_config=False)
print_data([data_source] if data_source else [])
else:
data_sources = DataClient().get_all()
print_data(data_sources)
def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_reference)
# Try with the raw ID
if not data_obj and data_id != normalized_data_reference:
data_obj = client.get(data_id)
return data_obj
def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
data_source.created_pretty,
data_source.state, data_source.size])
floyd_logger.info(tabulate(data_list, headers=headers))
@click.command()
@click.argument('id', nargs=1)
@click.option('--path', '-p',
help='Download files in a specific path from job output or a dataset')
def clone(id, path):
"""
- Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
if 'output' in id:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
if path:
# Download a directory from Dataset or Files
# Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/)
if '/datasets/' in id:
resource_type = 'data'
resource_id = data_source.id
else:
resource_type = 'files'
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
resource_id = experiment.id
data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}".format(floyd.floyd_host,
resource_type,
resource_id,
path)
else:
# Download the full Dataset
data_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
data_source.resource_id)
DataClient().download_tar(url=data_url,
untar=True,
delete_after_untar=True)
@click.command()
@click.argument('data_name', nargs=1)
def listfiles(data_name):
"""
List files in a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
# Depth-first search
dirs = ['']
paths = []
while dirs:
cur_dir = dirs.pop()
url = "/resources/{}/{}?content=true".format(data_source.resource_id, cur_dir)
response = DataClient().request("GET", url).json()
if response['skipped_files'] > 0:
floyd_logger.info("Warning: in directory '%s', %s/%s files skipped (too many files)", cur_dir, response['skipped_files'], response['total_files'])
files = response['files']
files.sort(key=lambda f: f['name'])
for f in files:
path = os.path.join(cur_dir, f['name'])
if f['type'] == 'directory':
path += os.sep
paths.append(path)
if f['type'] == 'directory':
dirs.append(os.path.join(cur_dir, f['name']))
for path in paths:
floyd_logger.info(path)
@click.command()
@click.argument('data_name', nargs=1)
@click.argument('path', nargs=1)
def getfile(data_name, path):
"""
Download a specific file from a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path)
fname = os.path.basename(path)
DataClient().download(url, filename=fname)
floyd_logger.info("Download finished")
@click.command()
@click.option('-u', '--url', is_flag=True, default=False,
help='Only print url for viewing data')
@click.argument('id', nargs=1, required=False)
def output(id, url):
"""
View the files from a dataset.
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
sys.exit()
data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name)
if url:
floyd_logger.info(data_url)
else:
floyd_logger.info("Opening output directory in your browser ...")
webbrowser.open(data_url)
@click.command()
@click.argument('ids', nargs=-1)
@click.option('-y', '--yes', is_flag=True, default=False,
help='Skip confirmation')
def delete(ids, yes):
"""
Delete datasets.
"""
failures = False
for id in ids:
data_source = get_data_object(id, use_data_config=True)
if not data_source:
failures = True
continue
data_name = normalize_data_name(data_source.name)
suffix = data_name.split('/')[-1]
if not suffix.isdigit():
failures = True
floyd_logger.error('%s is not a dataset, skipped.', id)
if suffix == 'output':
floyd_logger.error('To delete job output, please delete the job itself.')
continue
if not yes and not click.confirm("Delete Data: {}?".format(data_name),
abort=False,
default=False):
floyd_logger.info("Data %s: Skipped", data_name)
continue
if not DataClient().delete(data_source.id):
failures = True
else:
floyd_logger.info("Data %s: Deleted", data_name)
if failures:
sys.exit(1)
@click.command()
@click.argument('source')
def add(source):
"""
Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output
"""
new_data = DatasetClient().add_data(source)
print_data([DataClient().get(new_data['data_id'])])
data.add_command(clone)
data.add_command(delete)
data.add_command(init)
data.add_command(upload)
data.add_command(status)
data.add_command(output)
data.add_command(add)
data.add_command(listfiles)
data.add_command(getfile)