/
main.py
397 lines (320 loc) · 13.1 KB
/
main.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""
Usage: humu-download [options] EXPORT-FILE
humu-download -h
Download Humu data files from a subject table export into CSV data files.
Arguments:
EXPORT-FILE Humu subject export CSV file
Options:
--no-gui use plain text output only [default: false]
-d --dest-dir=DEST-DIR download destination directory. By default
a subdir of the current directory
named after the CSV file is used. The directory
is created if it does not exist. Any existing
data files in the directory are overwritten.
-c --chunk-size=CHUNK-SIZE number of bytes to process at a
time [default: 4096]
--keep-raw keep raw data files in addition to CSV
-h --help show help
-v --version show version
"""
import docopt
import requests
import pandas
import urwid
from urwid_timed_progress import TimedProgressBar
import csv
import os
import glob
import zipfile
import shutil
from . import __version__
class App(object):
def __init__(self, csv_file, dest_dir, chunk_size, keep_raw):
self.csv_file = csv_file
self.dest_dir = dest_dir
self.chunk_size = chunk_size
self.keep_raw = keep_raw
def read_csv_file(self):
self.files = []
with open(self.csv_file, 'r') as f:
lines = (line for line in f if not line.lstrip().startswith('#'))
reader = csv.DictReader(lines)
for row in reader:
for key in row.keys():
if key.endswith('_url'):
ds = key.rsplit('_', 1)[0]
url = row[key]
if url:
size = row['{}_size'.format(ds)]
if size:
size = int(size)
else:
size = 0
name = '{}-{}-{}'.format(row['ID'], row['_id'], ds)
self.files.append({
'data_series_name': ds,
'name': name.replace('/', '_'),
'url': url,
'size': size})
def download_files(self, *args, **kwargs):
done = sum([f['size'] for f in self.files])
if done != 0:
self.init_overall_progress(done)
self.status('starting download ...')
if not os.path.exists(self.dest_dir):
os.makedirs(self.dest_dir)
for f in self.files:
self.download_file(f)
self.status('download complete')
return self.convert_files()
def convert_files(self):
files = [f for f in self.files if f.get('download_complete')]
done = sum([f['actual_size'] for f in files])
if done != 0:
self.init_convert_progress(done)
self.status('converting {} data files to CSV'.format(len(files)))
for idx, f in enumerate(files):
self.status('converting {} of {} to CSV\n\n{}'.format(
idx + 1, len(files), f['hdf']))
self.convert_file(f)
self.update_convert_progress(f['actual_size'])
failures = [f for f in self.files if not f.get('success')]
if failures:
self.status('Could not process the following files,' +
' please re-export your data and try again:\n ' +
'\n '.join(f['name'] for f in failures))
else:
self.status('complete')
return True
def download_file(self, file):
file['hdf'] = os.path.join(self.dest_dir, file['name'])
self.status('downloading {} ...'.format(file['hdf']))
r = requests.get(file['url'], stream=True)
try:
r.raise_for_status()
except:
return False
estimated_size = file['size']
file['actual_size'] = int(r.headers.get('content-length', 0))
if file['actual_size'] != estimated_size:
done = (self.overall_progress.done +
file['actual_size'] - estimated_size)
if done != 0:
self.init_overall_progress(done)
if file['actual_size'] != 0:
with open(file['hdf'], 'wb') as f:
self.init_file_progress(file['actual_size'])
for chunk in r.iter_content(self.chunk_size):
f.write(chunk)
num_bytes = len(chunk)
self.update_file_progress(num_bytes)
file['download_complete'] = True
return True
def convert_file(self, file):
try:
df = pandas.read_hdf(file['hdf'], 'data')
file['csv'] = '{}.csv'.format(
os.path.join(self.dest_dir, file['name']))
df.to_csv(file['csv'],
header=[file['data_series_name']],
encoding='utf-8',
index_label='datetime')
file['success'] = True
if not self.keep_raw:
os.remove(file['hdf'])
except Exception as e:
file['success'] = False
return file['success']
class TextApp(App):
def run(self):
self.read_csv_file()
return self.download_files()
def status(self, msg):
print(msg)
def init_file_progress(self, size):
pass
def init_overall_progress(self, size):
pass
def update_overall_progress(self, size):
pass
def update_file_progress(self, size):
pass
def init_convert_progress(self, done):
pass
def update_convert_progress(self, size):
pass
def download_file(self, file):
file['hdf'] = os.path.join(self.dest_dir, file['name'])
self.status('downloading {} ...'.format(file['hdf']))
r = requests.get(file['url'], stream=True)
try:
r.raise_for_status()
except:
return False
estimated_size = file['size']
file['actual_size'] = int(r.headers.get('content-length', 0))
if file['actual_size'] != 0:
with open(file['hdf'], 'wb') as f:
self.init_file_progress(file['actual_size'])
for chunk in r.iter_content(self.chunk_size):
f.write(chunk)
num_bytes = len(chunk)
self.update_file_progress(num_bytes)
file['download_complete'] = True
return True
class GuiApp(App):
def __init__(self, *args, **kwargs):
super(GuiApp, self).__init__(*args, **kwargs)
palette = [
('normal', 'white', 'black', 'standout'),
('complete', 'white', 'dark magenta'),
('footer', 'white', 'dark gray'),
]
units = [
('bytes', 1),
('kB', 1000),
('MB', 1000000),
('GB', 1000000000)]
self.file_progress = TimedProgressBar('normal',
'complete',
label='Current File',
label_width=15,
units=units,
done=1)
self.overall_progress = TimedProgressBar('normal',
'complete',
label='Overall',
label_width=15,
units=units,
done=1)
self.convert_progress = TimedProgressBar('normal',
'complete',
label='',
label_width=0,
units=units,
done=1)
self._status = urwid.Text('')
download_progress = urwid.LineBox(urwid.Pile([
('pack', self.file_progress),
('pack', urwid.Divider()),
('pack', self.overall_progress)]),
title='Download Progress')
self.widgets = urwid.SimpleFocusListWalker([
download_progress,
urwid.Divider(),
self._status,
])
body_view = urwid.ListBox(self.widgets)
self.footer = urwid.Text('Ctrl-C to abort')
app_view = urwid.Frame(body_view,
footer=urwid.AttrWrap(self.footer, 'footer'))
def keypress(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
self.loop = urwid.MainLoop(app_view,
palette,
unhandled_input=keypress)
def status(self, msg):
self._status.set_text(msg)
self.loop.draw_screen()
def run(self):
self.read_csv_file()
self.loop.set_alarm_in(0.1, self.download_files)
self.loop.run()
def init_file_progress(self, size):
self.file_progress.reset()
self.file_progress.done = size
self.loop.draw_screen()
def init_overall_progress(self, size):
self.overall_progress.reset()
self.overall_progress.done = size
self.loop.draw_screen()
def update_overall_progress(self, size):
self.overall_progress.add_progress(size)
self.loop.draw_screen()
def update_file_progress(self, size):
self.file_progress.add_progress(size)
self.update_overall_progress(size)
self.loop.draw_screen()
def init_convert_progress(self, done):
self.convert_progress.add_progress(0, done=done)
# show convert progress just above status
self.widgets[-1:-1] = [
urwid.LineBox(self.convert_progress, title='Convert Progress'),
urwid.Divider()
]
def update_convert_progress(self, size):
self.convert_progress.add_progress(size)
def convert_files(self):
App.convert_files(self)
self.footer.set_text('q to exit')
def download_file(self, file):
file['hdf'] = os.path.join(self.dest_dir, file['name'])
self.status('downloading {} ...'.format(file['hdf']))
r = requests.get(file['url'], stream=True)
try:
r.raise_for_status()
except:
return False
estimated_size = file['size']
file['actual_size'] = int(r.headers.get('content-length', 0))
if file['actual_size'] != estimated_size:
done = (self.overall_progress.done +
file['actual_size'] - estimated_size)
if done != 0:
self.init_overall_progress(done)
if file['actual_size'] != 0:
with open(file['hdf'], 'wb') as f:
self.init_file_progress(file['actual_size'])
for chunk in r.iter_content(self.chunk_size):
f.write(chunk)
num_bytes = len(chunk)
self.update_file_progress(num_bytes)
file['download_complete'] = True
return True
def zipdir(path, ziph):
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
def main():
args = docopt.docopt(__doc__,
version='humu-download {}'.format(__version__))
csv_file = args['EXPORT-FILE']
# batch export mode
# If csv_file is actually a directory download all of the CSV files in
# each of its subdirs
if os.path.isdir(csv_file):
csv_files = glob.glob('{}/*/*.csv'.format(csv_file))
for csv_file in csv_files:
dest_dir = os.path.join(os.path.dirname(csv_file), 'to_zip')
app = TextApp(csv_file,
os.path.join(dest_dir, 'data'),
int(args['--chunk-size']),
False)
if app.run():
os.rename(csv_file,
os.path.join(os.path.dirname(csv_file),
'to_zip',
os.path.basename(csv_file)))
zip_filename = os.path.join(
os.path.join(os.path.dirname(csv_file)),
os.path.splitext(os.path.basename(csv_file))[0] + '.zip')
zipf = zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED)
zipdir(dest_dir, zipf)
zipf.close()
shutil.rmtree(dest_dir, ignore_errors=True)
else:
dest_dir = args.get('--dest-dir')
if not dest_dir:
dest_dir = os.path.splitext(os.path.basename(csv_file))[0]
if os.name != 'posix' or args['--no-gui']:
app_class = TextApp
else:
app_class = GuiApp
app = app_class(csv_file,
dest_dir,
int(args['--chunk-size']),
args['--keep-raw'])
app.run()
if __name__ == '__main__':
exit(main())