brkraw 0.3.11__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. brkraw/__init__.py +9 -3
  2. brkraw/apps/__init__.py +12 -0
  3. brkraw/apps/addon/__init__.py +30 -0
  4. brkraw/apps/addon/core.py +35 -0
  5. brkraw/apps/addon/dependencies.py +402 -0
  6. brkraw/apps/addon/installation.py +500 -0
  7. brkraw/apps/addon/io.py +21 -0
  8. brkraw/apps/hook/__init__.py +25 -0
  9. brkraw/apps/hook/core.py +636 -0
  10. brkraw/apps/loader/__init__.py +10 -0
  11. brkraw/apps/loader/core.py +622 -0
  12. brkraw/apps/loader/formatter.py +288 -0
  13. brkraw/apps/loader/helper.py +797 -0
  14. brkraw/apps/loader/info/__init__.py +11 -0
  15. brkraw/apps/loader/info/scan.py +85 -0
  16. brkraw/apps/loader/info/scan.yaml +90 -0
  17. brkraw/apps/loader/info/study.py +69 -0
  18. brkraw/apps/loader/info/study.yaml +156 -0
  19. brkraw/apps/loader/info/transform.py +92 -0
  20. brkraw/apps/loader/types.py +220 -0
  21. brkraw/cli/__init__.py +5 -0
  22. brkraw/cli/commands/__init__.py +2 -0
  23. brkraw/cli/commands/addon.py +327 -0
  24. brkraw/cli/commands/config.py +205 -0
  25. brkraw/cli/commands/convert.py +903 -0
  26. brkraw/cli/commands/hook.py +348 -0
  27. brkraw/cli/commands/info.py +74 -0
  28. brkraw/cli/commands/init.py +214 -0
  29. brkraw/cli/commands/params.py +106 -0
  30. brkraw/cli/commands/prune.py +288 -0
  31. brkraw/cli/commands/session.py +371 -0
  32. brkraw/cli/hook_args.py +80 -0
  33. brkraw/cli/main.py +83 -0
  34. brkraw/cli/utils.py +60 -0
  35. brkraw/core/__init__.py +13 -0
  36. brkraw/core/config.py +380 -0
  37. brkraw/core/entrypoints.py +25 -0
  38. brkraw/core/formatter.py +367 -0
  39. brkraw/core/fs.py +495 -0
  40. brkraw/core/jcamp.py +600 -0
  41. brkraw/core/layout.py +451 -0
  42. brkraw/core/parameters.py +781 -0
  43. brkraw/core/zip.py +1121 -0
  44. brkraw/dataclasses/__init__.py +14 -0
  45. brkraw/dataclasses/node.py +139 -0
  46. brkraw/dataclasses/reco.py +33 -0
  47. brkraw/dataclasses/scan.py +61 -0
  48. brkraw/dataclasses/study.py +131 -0
  49. brkraw/default/__init__.py +3 -0
  50. brkraw/default/pruner_specs/deid4share.yaml +42 -0
  51. brkraw/default/rules/00_default.yaml +4 -0
  52. brkraw/default/specs/metadata_dicom.yaml +236 -0
  53. brkraw/default/specs/metadata_transforms.py +92 -0
  54. brkraw/resolver/__init__.py +7 -0
  55. brkraw/resolver/affine.py +539 -0
  56. brkraw/resolver/datatype.py +69 -0
  57. brkraw/resolver/fid.py +90 -0
  58. brkraw/resolver/helpers.py +36 -0
  59. brkraw/resolver/image.py +188 -0
  60. brkraw/resolver/nifti.py +370 -0
  61. brkraw/resolver/shape.py +235 -0
  62. brkraw/schema/__init__.py +3 -0
  63. brkraw/schema/context_map.yaml +62 -0
  64. brkraw/schema/meta.yaml +57 -0
  65. brkraw/schema/niftiheader.yaml +95 -0
  66. brkraw/schema/pruner.yaml +55 -0
  67. brkraw/schema/remapper.yaml +128 -0
  68. brkraw/schema/rules.yaml +154 -0
  69. brkraw/specs/__init__.py +10 -0
  70. brkraw/specs/hook/__init__.py +12 -0
  71. brkraw/specs/hook/logic.py +31 -0
  72. brkraw/specs/hook/validator.py +22 -0
  73. brkraw/specs/meta/__init__.py +5 -0
  74. brkraw/specs/meta/validator.py +156 -0
  75. brkraw/specs/pruner/__init__.py +15 -0
  76. brkraw/specs/pruner/logic.py +361 -0
  77. brkraw/specs/pruner/validator.py +119 -0
  78. brkraw/specs/remapper/__init__.py +27 -0
  79. brkraw/specs/remapper/logic.py +924 -0
  80. brkraw/specs/remapper/validator.py +314 -0
  81. brkraw/specs/rules/__init__.py +6 -0
  82. brkraw/specs/rules/logic.py +263 -0
  83. brkraw/specs/rules/validator.py +103 -0
  84. brkraw-0.5.0.dist-info/METADATA +81 -0
  85. brkraw-0.5.0.dist-info/RECORD +88 -0
  86. {brkraw-0.3.11.dist-info → brkraw-0.5.0.dist-info}/WHEEL +1 -2
  87. brkraw-0.5.0.dist-info/entry_points.txt +13 -0
  88. brkraw/lib/__init__.py +0 -4
  89. brkraw/lib/backup.py +0 -641
  90. brkraw/lib/bids.py +0 -0
  91. brkraw/lib/errors.py +0 -125
  92. brkraw/lib/loader.py +0 -1220
  93. brkraw/lib/orient.py +0 -194
  94. brkraw/lib/parser.py +0 -48
  95. brkraw/lib/pvobj.py +0 -301
  96. brkraw/lib/reference.py +0 -245
  97. brkraw/lib/utils.py +0 -471
  98. brkraw/scripts/__init__.py +0 -0
  99. brkraw/scripts/brk_backup.py +0 -106
  100. brkraw/scripts/brkraw.py +0 -744
  101. brkraw/ui/__init__.py +0 -0
  102. brkraw/ui/config.py +0 -17
  103. brkraw/ui/main_win.py +0 -214
  104. brkraw/ui/previewer.py +0 -225
  105. brkraw/ui/scan_info.py +0 -72
  106. brkraw/ui/scan_list.py +0 -73
  107. brkraw/ui/subj_info.py +0 -128
  108. brkraw-0.3.11.dist-info/METADATA +0 -25
  109. brkraw-0.3.11.dist-info/RECORD +0 -28
  110. brkraw-0.3.11.dist-info/entry_points.txt +0 -3
  111. brkraw-0.3.11.dist-info/top_level.txt +0 -2
  112. tests/__init__.py +0 -0
  113. {brkraw-0.3.11.dist-info → brkraw-0.5.0.dist-info/licenses}/LICENSE +0 -0
brkraw/lib/utils.py DELETED
@@ -1,471 +0,0 @@
1
- from .errors import *
2
- from .reference import *
3
- import re
4
- import os
5
- import numpy as np
6
- from collections import OrderedDict
7
- from functools import partial, reduce
8
- from copy import copy as cp
9
- import time
10
-
11
-
12
- class TimeCounter:
13
- _start = None
14
-
15
- def __init__(self):
16
- self.reset()
17
-
18
- def reset(self):
19
- self._start = time.time()
20
-
21
- def time(self):
22
- return time.time() - self._start
23
-
24
-
25
- def load_param(stringlist):
26
- # JCAMP DX parser
27
- params = OrderedDict()
28
- param_addresses = list()
29
-
30
- for line_num, line in enumerate(stringlist):
31
- regex_obj = re.match(ptrn_param, line)
32
- # if line is key=value pair
33
- if regex_obj != None:
34
- # parse key and value
35
- key = re.sub(ptrn_param, r'\g<key>', line)
36
- value = re.sub(ptrn_param, r'\g<value>', line)
37
- # if key contains $
38
- if re.match(ptrn_key, key):
39
- # classify as parameter
40
- params[line_num] = PARAMETER, re.sub(ptrn_key, r'\g<key>', key), value
41
- param_addresses.append(line_num)
42
- else:
43
- # classify as file header
44
- params[line_num] = HEADER, key, value
45
- param_addresses.append(line_num)
46
- return params, param_addresses, stringlist
47
-
48
-
49
- def convert_string_to(string):
50
- string = string.strip()
51
- if re.match(ptrn_string, string):
52
- string = re.sub(ptrn_string, r'\g<string>', string).strip()
53
- if not string:
54
- return None
55
- else:
56
- if re.match(ptrn_float, string):
57
- return float(string)
58
- elif re.match(ptrn_integer, string):
59
- return int(string)
60
- elif re.match(ptrn_engnotation, string):
61
- return float(string)
62
- else:
63
- return string
64
-
65
-
66
- def convert_data_to(data, shape):
67
- # check if data is array
68
- if isinstance(data, str):
69
- is_bisarray = re.findall(ptrn_bisstring, data)
70
- if is_bisarray:
71
- is_bisarray = [convert_string_to(c) for c in is_bisarray]
72
- if len(is_bisarray) == 1:
73
- data = is_bisarray.pop()
74
- else:
75
- data = is_bisarray
76
- else:
77
-
78
- # [20210820] Add-paravision 360 related.
79
- m_all = re.findall(ptrn_at_array, data)
80
- m_all = set(m_all)
81
- m_all = list(m_all)
82
-
83
- for str_ptn in m_all:
84
- num_cnt = int(str_ptn[0])
85
- num_repeat = float(str_ptn[1])
86
- str_ptn = "@" + str_ptn[0] + "*(" + str_ptn[1] + ")"
87
-
88
- str_replace_old = str_ptn
89
- str_replace_new = [num_repeat for i in range(num_cnt)]
90
- str_replace_new = str(str_replace_new)
91
- str_replace_new = str_replace_new.replace(",", "")
92
- str_replace_new = str_replace_new.replace("[", "")
93
- str_replace_new = str_replace_new.replace("]", "")
94
- data = data.replace(str_replace_old, str_replace_new)
95
-
96
- if re.match(ptrn_complex_array, data):
97
- # data = re.sub(ptrn_complex_array, r'\g<comparray>', data)
98
- data_holder = cp(data)
99
- parser = {}
100
- level = 1
101
- while len(re.findall(ptrn_braces, data_holder)) != 0:
102
- for parsed in re.finditer(ptrn_braces, data_holder):
103
- key = 'level_{}'.format(level)
104
-
105
- cont_parser = []
106
- for cont in map(str.strip, parsed.group('contents').split(',')):
107
- cont = convert_data_to(cont, -1)
108
- if cont != None:
109
- cont_parser.append(cont)
110
- if key not in parser.keys():
111
- parser[key] = []
112
- parser[key].append(cont_parser)
113
- data_holder = data_holder.replace(parsed.group(0), '')
114
- level += 1
115
- del level
116
- data = parser
117
- else:
118
- if re.match(ptrn_string, data):
119
- data = re.sub(ptrn_string, r'\g<string>', data)
120
- else:
121
- is_array = re.findall(ptrn_array, data)
122
- # parse data shape
123
- if shape != -1:
124
- shape = re.sub(ptrn_array, r'\g<array>', shape)
125
- if ',' in shape:
126
- shape = [convert_string_to(c) for c in shape.split(',')]
127
-
128
- if is_array:
129
- is_array = [convert_string_to(c) for c in is_array]
130
- if any([',' in cell for cell in is_array]):
131
- data = [[convert_string_to(c) for c in cell.split(',')] for cell in is_array]
132
- else:
133
- if ',' in data:
134
- if re.findall(ptrn_arraystring, data):
135
- data = [convert_string_to(c) for c in data.split(' ')]
136
- else:
137
- data = [convert_string_to(c) for c in data.split(',')]
138
- else:
139
- if ' ' in data:
140
- data = [convert_string_to(c) for c in data.split(' ')]
141
- if isinstance(data, list):
142
- if isinstance(shape, list):
143
- if not any([isinstance(c, str) for c in data]):
144
- if not any([c is None for c in data]):
145
- data = np.asarray(data).reshape(shape)
146
- elif isinstance(data, str):
147
- data = convert_string_to(data)
148
- return data
149
-
150
-
151
- def get_value(pars, key):
152
- if key not in pars.parameters.keys():
153
- return None
154
- else:
155
- return pars.parameters[key]
156
-
157
-
158
- def is_all_element_same(listobj):
159
- if listobj is None:
160
- return True
161
- else:
162
- return all(map(partial(lambda x, y: x == y, y=listobj[0]), listobj))
163
-
164
-
165
- def is_numeric(x):
166
- return any([isinstance(x, float), isinstance(x, int)])
167
-
168
-
169
- def multiply_all(list):
170
- return reduce(lambda x, y: x*y, list)
171
-
172
-
173
- # META handler
174
- def meta_get_value(value, acqp, method, visu_pars):
175
- if isinstance(value, str):
176
- return meta_check_source(value, acqp, method, visu_pars)
177
- elif isinstance(value, dict):
178
- if is_keywhere(value):
179
- return meta_check_where(value, acqp, method, visu_pars)
180
- elif is_keyindex(value):
181
- return meta_check_index(value, acqp, method, visu_pars)
182
- elif is_express(value):
183
- return meta_check_express(value, acqp, method, visu_pars)
184
- else:
185
- parser = dict()
186
- for k, v in value.items():
187
- parser[k] = meta_get_value(v, acqp, method, visu_pars)
188
- return parser
189
- elif isinstance(value, list):
190
- parser = []
191
- max_index = len(value) - 1
192
- for i, vi in enumerate(value):
193
- val = meta_get_value(vi, acqp, method, visu_pars)
194
- if val != None:
195
- if val == vi:
196
- if i == max_index:
197
- parser.append(val)
198
- else:
199
- parser.append(val)
200
- if len(parser) > 0:
201
- return parser[0]
202
- else:
203
- return None
204
- else:
205
- return value
206
-
207
-
208
- def is_keywhere(value):
209
- if all([k in value.keys() for k in ['key', 'where']]):
210
- return True
211
- else:
212
- return False
213
-
214
-
215
- def is_keyindex(value):
216
- if all([k in value.keys() for k in ['key', 'idx']]):
217
- return True
218
- else:
219
- return False
220
-
221
-
222
- def is_express(value):
223
- if any([k in value.keys() for k in ['Equation']]):
224
- return True
225
- else:
226
- return False
227
-
228
-
229
- def meta_check_where(value, acqp, method, visu_pars):
230
- val = meta_get_value(value['key'], acqp, method, visu_pars)
231
- if val != None:
232
- if isinstance(value['where'], str):
233
- if value['where'] not in val:
234
- return None
235
- else:
236
- return val.index(value['where'])
237
- else:
238
- where = meta_get_value(value['where'], acqp, method, visu_pars)
239
- return val.index(where)
240
- else:
241
- return None
242
-
243
-
244
- def meta_check_index(value, acqp, method, visu_pars):
245
- val = meta_get_value(value['key'], acqp, method, visu_pars)
246
- if val != None:
247
- if isinstance(value['idx'], int):
248
- return val[value['idx']]
249
- else:
250
- idx = meta_get_value(value['idx'], acqp, method, visu_pars)
251
- if idx != None:
252
- return val[idx]
253
- else:
254
- return None
255
- else:
256
- return None
257
-
258
-
259
- def meta_check_express(value, acqp, method, visu_pars):
260
- lcm = locals()
261
- for k, v in value.items():
262
- if k != 'Equation':
263
- exec('global {}'.format(k))
264
- val = meta_get_value(v, acqp, method, visu_pars)
265
- exec('{} = {}'.format(k, val))
266
- try:
267
- exec("output = {}".format(value['Equation']), globals(), lcm)
268
- return lcm['output']
269
- except:
270
- return None
271
-
272
-
273
- def meta_check_source(key_string, acqp, method, visu_pars):
274
- pool = [acqp, method, visu_pars]
275
- key_exist = [key_string in p.parameters.keys() for p in pool]
276
- for i, ans in enumerate(key_exist):
277
- if ans:
278
- return get_value(pool[i], key_string)
279
- return key_string
280
-
281
-
282
- def yes_or_no(question):
283
- while True:
284
- reply = str(input(question + ' (y/n): ')).lower().strip()
285
- if reply[:1] == 'y':
286
- return True
287
- elif reply[:1] == 'n':
288
- return False
289
- else:
290
- print(' The answer is invalid!')
291
-
292
-
293
- def convert_unit(size_in_bytes, unit):
294
- """ Convert the size from bytes to other units like KB, MB or GB"""
295
- size = float(size_in_bytes)
296
- if unit == 1:
297
- return size / 1024
298
- elif unit == 2:
299
- return size / (1024 * 1024)
300
- elif unit == 3:
301
- return size / (1024 * 1024 * 1024)
302
- elif unit == 4:
303
- return size / (1024**unit)
304
- else:
305
- return int(size)
306
-
307
-
308
- def get_dirsize(dir_path):
309
- unit_dict = {0: 'B',
310
- 1: 'KB',
311
- 2: 'MB',
312
- 3: 'GB',
313
- 4: 'TB'}
314
- dir_size = 0
315
- for root, dirs, files in os.walk(dir_path):
316
- for f in files:
317
- fp = os.path.join(root, f)
318
- if not os.path.islink(fp):
319
- dir_size += os.path.getsize(fp)
320
-
321
- unit = int(len(str(dir_size)) / 3)
322
- return convert_unit(dir_size, unit), unit_dict[unit]
323
-
324
-
325
- def get_filesize(file_path):
326
- unit_dict = {0: 'B',
327
- 1: 'KB',
328
- 2: 'MB',
329
- 3: 'GB'}
330
- file_size = os.path.getsize(file_path)
331
-
332
- unit = int(len(str(file_size)) / 3)
333
- return convert_unit(file_size, unit), unit_dict[unit]
334
-
335
-
336
- def bids_validation(df, idx, key, val, num_char_allowed, dtype=None):
337
- import string
338
- col = string.ascii_uppercase[df.columns.tolist().index(key)]
339
- special_char = re.compile(r'[^0-9a-zA-Z]')
340
- str_val = str(val)
341
- loc = 'col,row:[{},{}]'.format(col, idx + 2)
342
- if len(str_val) > num_char_allowed:
343
- message = "{} You can't use more than {} characters.".format(loc, num_char_allowed)
344
- raise InvalidValueInField(message)
345
- matched = special_char.search(str_val)
346
- if matched != None:
347
- if ' ' in matched.group():
348
- message = "{} Empty string is not allowed.".format(loc)
349
- else:
350
- message = "{} Special characters are not allowed.".format(loc)
351
- raise InvalidValueInField(message)
352
- if dtype != None:
353
- try:
354
- dtype(val)
355
- except:
356
- message = "{} Invalid data type. Value must be {}.".format(loc, dtype.__name__)
357
- raise InvalidValueInField(message)
358
- return True
359
-
360
-
361
- def get_bids_ref_obj(ref_path, row):
362
- import json
363
- if os.path.exists(ref_path) and ref_path.lower().endswith('.json'):
364
- ref_data = json.load(open(ref_path))
365
- ref = ref_data['common']
366
- if row.modality in ['bold', 'cbv', 'epi']:
367
- if 'func' in ref_data.keys():
368
- for k, v in ref_data['func'].items():
369
- if k in ref.keys():
370
- raise InvalidApproach('Duplicated key is found at func: {}'.format(k))
371
- else:
372
- ref[k] = v
373
- # the below may not optimal for Bruker system,
374
- # only fieldmap and magnitude
375
- if row.modality in ['fieldmap', 'phase1', 'phase2',
376
- 'phasediff', 'magnitude',
377
- 'magnitude1', 'magnitude2']:
378
- if 'fmap' in ref_data.keys():
379
- for k, v in ref_data['fmap'].items():
380
- if k in ref.keys():
381
- raise InvalidApproach('Duplicated key is found at func: {}'.format(k))
382
- else:
383
- ref[k] = v
384
- else:
385
- ref = None
386
- return ref
387
-
388
-
389
- def build_bids_json(dset, row, fname, json_path, slope=False, offset=False):
390
- import pandas as pd
391
-
392
- if pd.notnull(row.Start) or pd.notnull(row.End):
393
- crop = [int(row.Start), int(row.End)]
394
- else:
395
- crop = None
396
- if dset.is_multi_echo(row.ScanID, row.RecoID): # multi_echo
397
- nii_objs = dset.get_niftiobj(row.ScanID, row.RecoID, crop=crop, slope=slope, offset=offset)
398
- for echo, nii in enumerate(nii_objs):
399
- # caught a bug here for multiple echo, changed fname to currentFileName
400
- currentFileName = '{}_echo-{}_{}'.format(fname, echo + 1, row.modality)
401
- output_path = os.path.join(row.Dir, currentFileName)
402
- nii.to_filename('{}.nii.gz'.format(output_path))
403
- if json_path:
404
- ref = get_bids_ref_obj(json_path, row)
405
- dset.save_json(row.ScanID, row.RecoID, currentFileName, dir=row.Dir,
406
- metadata=ref, condition=['me', echo])
407
- else:
408
- fname = '{}_{}'.format(fname, row.modality)
409
- dset.save_as(row.ScanID, row.RecoID, fname, dir=row.Dir, crop=crop, slope=slope, offset=offset)
410
- if re.search('dwi', row.modality, re.IGNORECASE):
411
- # DTI parameter (FSL style)
412
- dset.save_bdata(row.ScanID, fname, dir=row.Dir)
413
- if json_path:
414
- ref = get_bids_ref_obj(json_path, row)
415
- if re.search('fieldmap', row.modality, re.IGNORECASE):
416
- condition = ['fm', None]
417
- else:
418
- condition = None
419
- if re.search('magnitude', row.modality, re.IGNORECASE):
420
- pass # magnitude data does not require JSON (BIDS)
421
- else:
422
- dset.save_json(row.ScanID, row.RecoID, fname, dir=row.Dir,
423
- metadata=ref, condition=condition)
424
-
425
-
426
- def encdir_code_converter(enc_param):
427
- # for PV 5.1, #TODO: incompleted code.
428
- if enc_param == 'col_dir':
429
- return ['read_enc', 'phase_enc']
430
- elif enc_param == 'row_dir':
431
- return ['phase_enc', 'read_enc']
432
- elif enc_param == 'col_slice_dir':
433
- return ['read_enc', 'phase_enc', 'slice_enc']
434
- elif enc_param == 'row_slice_dir':
435
- return ['phase_enc', 'read_enc', 'slice_enc']
436
- else:
437
- raise Exception(ERROR_MESSAGES['PhaseEncDir'])
438
-
439
-
440
- def mkdir(path):
441
- try:
442
- os.stat(path)
443
- except FileNotFoundError or OSError:
444
- os.makedirs(path)
445
- except:
446
- raise UnexpectedError
447
-
448
-
449
- # brkraw script
450
- def set_rescale(args):
451
- if not args.ignore_rescale:
452
- if args.ignore_slope:
453
- slope = None
454
- else:
455
- slope = False
456
- if args.ignore_offset:
457
- offset = None
458
- else:
459
- offset = False
460
- else:
461
- slope = None
462
- offset = None
463
- return slope, offset
464
-
465
-
466
- def save_meta_files(study, args, scan_id, reco_id, output_fname):
467
- method = study._pvobj._method[scan_id].parameters['Method']
468
- if re.search('dti', method, re.IGNORECASE):
469
- study.save_bdata(scan_id, output_fname)
470
- if args.bids:
471
- study.save_json(scan_id, reco_id, output_fname)
File without changes
@@ -1,106 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from .. import __version__
3
- from ..lib.backup import BackupCacheHandler
4
- import argparse
5
- import datetime
6
-
7
-
8
- def main():
9
- parser = argparse.ArgumentParser(prog='brk-backup',
10
- description="BrkRaw command-line interface for archiving")
11
- parser.add_argument("-v", "--version", action='version', version='%(prog)s v{}'.format(__version__))
12
-
13
- subparsers = parser.add_subparsers(title='Sub-commands',
14
- description='brk-backup provides convenient tool '
15
- 'for archiving and check the status.',
16
- help='description',
17
- dest='function',
18
- metavar='command')
19
-
20
- raw_path_str = "The directory of raw data of current user in ParaVision system."
21
- arc_path_str = "The directory of archived data. It must be mounted into ParaVision system."
22
- logging_str = "option for logging output instead printing"
23
-
24
- # added function
25
- archived = subparsers.add_parser("archived", help='Scan the status of archived data')
26
- review = subparsers.add_parser("review", help='Review the confliction between raw data and archived data')
27
- backup = subparsers.add_parser("backup", help='Archive the raw data. must be performed after review')
28
- clean = subparsers.add_parser("clean", help='Clean the archived that contains any issue')
29
-
30
- # options for archived function
31
- archived.add_argument("raw_path", help=raw_path_str, type=str)
32
- archived.add_argument("archived_path", help=arc_path_str, type=str)
33
- archived.add_argument("-l", "--logging", help=logging_str, action='store_true')
34
-
35
- # options for review function
36
- review.add_argument("raw_path", help=raw_path_str, type=str)
37
- review.add_argument("archived_path", help=arc_path_str, type=str)
38
- review.add_argument("-l", "--logging", help=logging_str, action='store_true')
39
-
40
- # options for backup function
41
- backup.add_argument("raw_path", help=raw_path_str, type=str)
42
- backup.add_argument("archived_path", help=arc_path_str, type=str)
43
- backup.add_argument("-l", "--logging", help=logging_str, action='store_true')
44
-
45
- # options for clean function
46
- clean.add_argument("raw_path", help=raw_path_str, type=str)
47
- clean.add_argument("archived_path", help=arc_path_str, type=str)
48
-
49
- # filename definitions for logging
50
- now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
51
- log_fname = 'brk-backup_{}.log'.format(now)
52
- lst_fname = 'brk-backup_archived_{}.log'.format(now)
53
- rvw_fname = 'brk-backup_review_{}.log'.format(now)
54
-
55
- # initial argument parsing
56
- args = parser.parse_args()
57
-
58
- # code for archived function
59
- if args.function == 'archived':
60
- rpath = args.raw_path
61
- bpath = args.archived_path
62
- handler = BackupCacheHandler(raw_path=rpath, backup_path=bpath)
63
- handler.scan()
64
- if args.logging:
65
- with open(lst_fname, 'w') as f:
66
- handler.print_completed(fobj=f)
67
- handler.print_completed()
68
-
69
- # code for review function
70
- elif args.function == 'review':
71
- rpath = args.raw_path
72
- bpath = args.archived_path
73
- handler = BackupCacheHandler(raw_path=rpath, backup_path=bpath)
74
- handler.scan()
75
- if args.logging:
76
- with open(rvw_fname, 'w') as f:
77
- handler.print_status(fobj=f)
78
- else:
79
- handler.print_status()
80
-
81
- # code for backup function
82
- elif args.function == 'backup':
83
- rpath = args.raw_path
84
- bpath = args.archived_path
85
- handler = BackupCacheHandler(raw_path=rpath, backup_path=bpath)
86
- handler.scan()
87
- if args.logging:
88
- with open(log_fname, 'w') as f:
89
- handler.backup(fobj=f)
90
- else:
91
- handler.backup()
92
-
93
- # code for clean function
94
- elif args.function == 'clean':
95
- rpath = args.raw_path
96
- bpath = args.archived_path
97
- handler = BackupCacheHandler(raw_path=rpath, backup_path=bpath)
98
- handler.scan()
99
- handler.clean()
100
-
101
- else:
102
- parser.print_help()
103
-
104
-
105
- if __name__ == '__main__':
106
- main()