-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_data.py
executable file
·1762 lines (1582 loc) · 70.6 KB
/
import_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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
"""See the epilog for detailed information."""
import argparse
import ast
import datetime
import hashlib
import mimetypes
import os
import pathlib as pp
import re
import subprocess
import sys
import time
import warnings # to suppress openpyxl warnings
from base64 import b64encode
from collections import Counter, OrderedDict
import gspread
# https://github.com/ahupp/python-magic
# this is the site for python-magic in case we need it
import magic # install me with 'pip install python-magic'
import openpyxl
import requests
from dcicutils import ff_utils
from gspread.exceptions import GSpreadException
from openpyxl.utils.exceptions import InvalidFileException
from wranglertools.get_field_info import (FDN_Connection, FDN_Key,
_remove_all_from_types,
create_common_arg_parser,
sheet_order)
def getArgs(): # pragma: no cover
parser = argparse.ArgumentParser(
parents=[create_common_arg_parser()],
description=__doc__, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('infile',
help="the datafile containing object data to import")
parser.add_argument('--update',
default=False,
action='store_true',
help="Let the script PATCH the data. Default is False")
parser.add_argument('--patchall',
default=False,
action='store_true',
help="PATCH existing objects. Default is False \
and will only PATCH with user override")
parser.add_argument('--remote',
default=False,
action='store_true',
help="will skip attribution prompt \
needed for automated submissions")
parser.add_argument('--lab',
help="When using --remote can pass in a valid lab identifier \
eg. uuid or @id to add attribution - must be able to submit for lab and \
not needed if only submit for a single lab.")
parser.add_argument('--award',
help="When using --remote if you are submitting for a lab with multiple awards \
can pass a valid award identifier eg. uuid or @id to add attribution \
not needed if there is only one award associated with the submitting lab.")
parser.add_argument('--novalidate',
default=False,
action='store_true',
help="Will skip pre-validation of workbook")
args = parser.parse_args()
_remove_all_from_types(args)
return args
EPILOG = '''
This script takes in a spreadsheet workbook file with the data
This is a dryrun-default script, run with --update, --patchall or both (--update --patchall)
to actually submit data to the portal
By DEFAULT:
If there is a uuid, @id, accession, or previously submitted alias in the document:
Use '--patchall' if you want to patch ALL objects in your document and ignore that message
If you want to upload new items(no existing object identifiers are found),
in the document you need to use '--update' for POSTing to occur
Defining Object type:
Each "sheet" of the excel file is named after the object type you are uploading,
with the format used on http://data.4dnucleome.org//profiles/
Ex: ExperimentHiC, Biosample, Document, BioFeature
If you only want to submit a subset of sheets in a workbook use the --type option with the
sheet name Ex: %(prog)s mydata.xlxs --type ExperimentHiC
The name of each sheet should be the names of the object type.
Ex: Award, Lab, BioFeature, etc.
The first row of the sheets should be the field names
Ex: aliases, experiment_type, etc.
To upload objects with attachments, use the column titled "attachment"
containing the full path to the file you wish to attach
To delete a field, use the keyword "*delete*" as the value.
For more details:
please see README.rst
'''
# list of [sheet, [fields]] that need to be patched as a second step
# should be in sync with loadxl.py in fourfront
list_of_loadxl_fields = [
['Document', ['references']],
['User', ['lab', 'submits_for']],
['ExperimentType', ['sop', 'reference_pubs']],
['Biosample', ['biosample_relation']],
['Experiment', ['experiment_relation']],
['ExperimentMic', ['experiment_relation']],
['ExperimentHiC', ['experiment_relation']],
['ExperimentSeq', ['experiment_relation']],
['ExperimentTsaseq', ['experiment_relation']],
['ExperimentDamid', ['experiment_relation']],
['ExperimentChiapet', ['experiment_relation']],
['ExperimentAtacseq', ['experiment_relation']],
['ExperimentCaptureC', ['experiment_relation']],
['ExperimentRepliseq', ['experiment_relation']],
['FileFastq', ['related_files']],
['FileReference', ['related_files']],
['FileCalibration', ['related_files']],
['FileMicroscopy', ['related_files']],
['FileProcessed', ['related_files', 'produced_from']],
['Individual', ['individual_relation']],
['IndividualChicken', ['individual_relation']],
['IndividualFly', ['individual_relation']],
['IndividualHuman', ['individual_relation']],
['IndividualMouse', ['individual_relation']],
['IndividualPrimate', ['individual_relation']],
['IndividualZebrafish', ['individual_relation']],
['Publication', ['exp_sets_prod_in_pub', 'exp_sets_used_in_pub']]
]
ALLOWED_MIMES = (
'application/pdf',
'application/zip',
'text/plain',
'text/tab-separated-values',
'text/html',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'image/png',
'image/jpeg',
'image/gif',
'image/tiff',
)
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
def md5(path_string):
path = pp.Path(path_string).expanduser()
md5sum = hashlib.md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1024*1024), b''):
md5sum.update(chunk)
return md5sum.hexdigest()
class WebFetchException(Exception):
"""
custom exception to raise if http fetch fails
"""
pass
def google_authenticate():
gsauth = None
creddir = pp.Path(__file__).parent.joinpath('.config', 'gspread')
gsauth = gspread.oauth(
credentials_filename=creddir.joinpath('credentials.json'),
authorized_user_filename=creddir.joinpath('authorized_user.json'),
scopes=SCOPES
)
return gsauth
def mime_allowed(path, ok_mimes):
filename = pp.PurePath(path).name
guessed_mime = mimetypes.guess_type(path)[0]
detected_mime = magic.from_file(path, mime=True)
if guessed_mime not in ok_mimes:
print("Unallowed file type for %s" % filename)
return False
# NOTE: this whole guesssing and detecting bit falls apart for zip files which seems a bit dodgy
# some .zip files are detected as generic application/octet-stream but don't see a good way to verify
# basically relying on extension with a little verification by magic for most file types
if detected_mime != guessed_mime and guessed_mime != 'application/zip':
print('Wrong extension for %s: %s' % (detected_mime, filename))
return False
return guessed_mime
def attachment(path):
"""Create an attachment upload object from a filename and embed the attachment as a data url.
NOTE: a url can be used but path must end in filename with extension that will match
the magic detected MIME type of that file and be one of the allowed mime types
"""
url_attach = False
if path.startswith('~'):
path = str(pp.Path(path).expanduser())
if not pp.Path(path).is_file():
# if the path does not exist, check if it works as a URL
try:
r = requests.get(path)
except Exception:
raise WebFetchException(
"\nERROR : The 'attachment' field has INVALID FILE PATH or URL ({})\n".format(path))
else:
# if it works as a URL, but does not return 200
if r.status_code != 200: # pragma: no cover
raise Exception("\nERROR : The 'attachment' field has INVALID URL ({})\n".format(path))
# parse response
path = path.split("/")[-1]
try:
with open(path, "wb") as outfile:
outfile.write(r.content)
url_attach = True
except Exception as e:
raise Exception("\nERROR : Cannot write a tmp file to disk - {}".format(e))
attach = {}
filename = pp.PurePath(path).name
guessed_mime = mimetypes.guess_type(path)[0]
detected_mime = magic.from_file(path, mime=True)
# NOTE: this whole guessing and detecting bit falls apart for zip files which seems a bit dodgy
# some .zip files are detected as generic application/octet-stream but don't see a good way to verify
# basically relying on extension with a little verification by magic for most file types
if guessed_mime not in ALLOWED_MIMES:
raise ValueError("Unallowed file type for %s" % filename)
if detected_mime != guessed_mime and guessed_mime != 'application/zip':
raise ValueError('Wrong extension for %s: %s' % (detected_mime, filename))
with open(path, 'rb') as stream:
attach = {
'download': filename,
'type': guessed_mime,
'href': 'data:%s;base64,%s' % (guessed_mime, b64encode(stream.read()).decode('ascii'))
}
if url_attach:
pp.Path(path).unlink()
return attach
def digest_xlsx(filename):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
book = openpyxl.load_workbook(filename)
except InvalidFileException as e:
if filename.endswith('.xls'):
print("WARNING - Old xls format not supported - please save your workbook as xlsx")
else:
print("ERROR - ", e)
sys.exit(1)
sheets = book.sheetnames
return book, sheets
def open_gsheets(gsid, gauth):
wkbk = gauth.open_by_key(gsid)
sheets = [sh.title for sh in wkbk.worksheets()]
return wkbk, sheets
def get_workbook(inputname, booktype, gauth=None):
if booktype == 'excel':
return digest_xlsx(inputname)
elif booktype == 'gsheet':
if not gauth:
raise GSpreadException("Google authentication problem")
return open_gsheets(inputname, gauth)
def reader(workbook, sheetname=None, booktype=None):
"""Read named sheet or first and only sheet from xlsx or google sheets file.
Assume excel by default - will choke if no booktype and not excel"""
sheet = None
if not booktype or booktype == 'excel':
if sheetname is None:
sheet = workbook.worksheets[0]
else:
try:
sheet = workbook[sheetname]
except Exception as e:
print(e)
print(sheetname)
print("ERROR: Can not find the collection sheet in excel file (openpyxl error)")
return
elif booktype == 'gsheet':
if sheetname is None:
sheet = workbook.get_worksheet(0)
else:
try:
sheet = workbook.worksheet(sheetname)
except Exception as e:
print(e)
print(sheetname)
print("ERROR: Can not find the collection sheet in excel file (gspread error)")
return
# Generator that gets rows from excel sheet
# NB we have a lot of empty no formatting rows added (can we get rid of that)
# or do we need to be careful to check for the first totally emptyvalue row?
return row_generator(sheet, booktype)
def row_generator(sheet, booktype=None):
"""Generator that gets rows from excel sheet
Note that this currently checks to see if a row is empty and if so stops
This is needed as plain text formatting of cells is recognized as data
"""
if not booktype or booktype == 'excel':
for row in sheet.rows:
vals = [cell_value(cell) for cell in row]
if not any([v for v in vals]):
return
else:
yield vals
else:
# no formatting here assuming all are strings
all_vals = sheet.get_values()
for row in all_vals:
yield row
def cell_value(cell):
"""Get cell value from excel. [From Submit4DN]"""
ctype = cell.data_type
value = cell.value
if ctype == openpyxl.cell.cell.TYPE_ERROR: # pragma: no cover
raise ValueError('Cell %s contains a cell error' % str(cell.coordinate))
elif ctype == openpyxl.cell.cell.TYPE_BOOL:
boolstr = str(value).strip()
if boolstr == 'TRUE':
return True
elif boolstr == 'FALSE':
return False
else:
return value
elif ctype in (openpyxl.cell.cell.TYPE_NUMERIC, openpyxl.cell.cell.TYPE_NULL):
if isinstance(value, float):
if value.is_integer():
value = int(value)
if not value:
return ''
return value
elif isinstance(value, openpyxl.cell.cell.TIME_TYPES):
if isinstance(value, datetime.datetime):
if value.time() == datetime.time(0, 0, 0):
return value.date().isoformat()
else: # pragma: no cover
return value.isoformat()
else:
return value.isoformat()
elif ctype in (openpyxl.cell.cell.TYPE_STRING, openpyxl.cell.cell.TYPE_INLINE):
return value.strip()
raise ValueError(
'Cell %s is not an acceptable cell type' % str(cell.coordinate)
) # pragma: no cover
def data_formatter(value, val_type, field=None):
"""Return formatted data."""
# If val_type is int/num, but the value is not
# this function will just return the string
# schema validation will report the error
try:
if val_type in ["int", "integer"]:
return int(value)
elif val_type in ["num", "number"]:
return float(value)
elif val_type in ["list", "array"]:
data_list = value.strip("[\']").split(",")
return [data.strip() for data in data_list]
elif val_type == 'boolean':
return value
else:
# default assumed to be string
return str(value).strip()
except ValueError: # pragma: no cover
return str(value).strip()
def get_field_name(field_name):
"""handle type at end, plus embedded objets."""
field = field_name.replace('*', '')
field = field.split(':')[0]
return field.split(".")[0]
def get_sub_field(field_name):
"""Construct embeded field names."""
try:
return field_name.split(".")[1].rstrip('-0123456789')
except Exception: # pragma: no cover
return ''
def get_field_type(field_name):
"""Grab old style (ENCODE) data field type."""
try:
return field_name.split(":")[1]
except IndexError:
return "string"
def is_embedded_field(field_name):
"""See if field is embedded."""
return '.' in field_name
def get_sub_field_number(field_name):
"""Name clearing for multiple objects."""
field_name = field_name.replace('*', '')
field = field_name.split(":")[0]
try:
return int(field.split("-")[1])
except Exception:
return 0
def build_field(field, field_data, field_type):
if field_data is False:
pass
elif not field_data or not field:
return None
patch_field_name = get_field_name(field)
if not field_type:
field_type = get_field_type(field)
if ',' in field_type:
field_type, subfield_type = [s.strip() for s in field_type.split(",")]
if 'array' in field_type:
field_type = 'array'
if is_embedded_field(field):
sub_field = get_sub_field(field)
return build_field(sub_field, field_data, subfield_type)
else:
patch_field_data = data_formatter(field_data, field_type, field)
return {patch_field_name: patch_field_data}
def fix_attribution(sheet, post_json, connection):
if sheet.lower() not in ['lab', 'award', 'user', 'organism', 'ontologyterm']:
if not post_json.get('lab'):
post_json['lab'] = connection.lab
if not post_json.get('award'):
post_json['award'] = connection.award
return post_json
def parse_exception(e):
"""ff_utils functions raise an exception when the expected code is not returned.
This response is a pre-formatted text, and this function will get the resonse json
out of it."""
try:
# try parsing the exception
text = e.args[0]
index = text.index('Reason: ')
resp_text = text[index + 8:]
resp_dict = ast.literal_eval(resp_text)
return resp_dict
# if not re-raise
except Exception: # pragma: no cover
raise e
def get_existing(post_json, connection):
"""Get the entry that will be patched from the server."""
# get all possible identifier from the json
all_ids = []
for identifier in ["uuid", "accession", "@id"]:
if post_json.get(identifier):
all_ids.append(post_json[identifier])
# also look for all aliases
if post_json.get("aliases"):
# weird precaution in case there are 2 aliases, 1 exisitng , 1 new
all_ids.extend(post_json['aliases'])
# look if post_json has these 3 identifier
temp = {}
uuids = []
for an_id in all_ids:
try:
temp = ff_utils.get_metadata(an_id, key=connection.key, add_on="frame=object")
except Exception as e:
exc = parse_exception(e)
# if the item does not exist get_metadata will raise an exceptions
# see if the exception message has 404, then continue, if not throw that exception
if exc['code'] == 404:
temp = {}
else:
raise e
if temp.get("uuid"):
uuids.append(temp.get("uuid"))
# check if all existing identifiers point to the same object
unique_uuids = list(set(uuids))
# if no existing information
if len(unique_uuids) == 0:
return {}
# if everything is as expected
elif len(unique_uuids) == 1:
temp = ff_utils.get_metadata(unique_uuids[0], key=connection.key, add_on="frame=object")
return temp
# funky business not allowed, if identifiers point to different objects
else: # pragma: no cover
print("ERROR - Personality disorder - ERROR")
print("Used identifiers (aliases, uuid, accession, @id) point to following different existing items")
print(unique_uuids)
return
def get_f_type(field, fields2types):
return fields2types.get(field, None)
def add_to_mistype_message(item='', itype='', ftype='', msg=''):
toadd = "ERROR: '%s' is " % item
if 'HTTPNotFound' in itype:
toadd += 'NOT FOUND '
else:
toadd += 'TYPE %s ' % itype
return msg + toadd + '- THE REQUIRED TYPE IS %s\n' % ftype
def validate_item(itemlist, typeinfield, alias_dict, connection):
msg = ''
pattern = re.compile(r"/[\w-]+/\w")
for item in itemlist:
if item in alias_dict:
itemtype = alias_dict[item]
if typeinfield not in itemtype:
# need special cases for FileSet and ExperimentSet?
msg = add_to_mistype_message(item, itemtype, typeinfield, msg)
else:
# check for fully qualified path i.e. /labs/4dn-dcic-lab/
match = pattern.match(item)
if not item.startswith('/'):
item = '/' + item
match = pattern.match(item)
if match is None:
item = '/' + typeinfield + item
try:
res = ff_utils.get_metadata(item, key=connection.key, add_on="frame=object")
except Exception as problem:
res = parse_exception(problem)
itemtypes = res.get('@type')
if itemtypes:
if typeinfield not in itemtypes:
msg = add_to_mistype_message(item, itemtypes[0], typeinfield, msg)
return msg.rstrip()
def validate_string(strings, alias_dict):
"""check if the string value is in the aliases list."""
msg = ''
for s in strings:
if alias_dict.get(s, None) is not None:
msg = msg + "WARNING: ALIAS %s USED IN string Field\n" % s
return msg.rstrip()
def _convert_to_array(s, is_array):
if is_array:
return [i.strip() for i in s.split(',')]
return [s.strip()]
def validate_field(field_data, field_type, aliases_by_type, connection):
to_trim = 'array of embedded objects, '
is_array = False
msg = None
field_data = data_formatter(field_data, field_type)
if field_type.startswith(to_trim):
field_type = field_type.replace(to_trim, '')
if 'array' in field_type:
is_array = True
if 'Item:' in field_type:
_, itemtype = field_type.rsplit(':', 1)
items = _convert_to_array(field_data, is_array)
msg = validate_item(items, itemtype, aliases_by_type, connection)
elif 'string' in field_type:
strings = _convert_to_array(field_data, is_array)
msg = validate_string(strings, aliases_by_type)
elif 'boolean' in field_type:
pass # for now
return msg
def pre_validate_json(post_json, fields2types, aliases_by_type, connection):
report = []
for field, field_data in post_json.items():
# ignore commented out fields
if field.startswith('#'):
continue
# ignore empty fields
if not field_data:
continue
# ignore certain fields - aliases validated before
# source_experiments and produced_from hold strings of aliases by design
if field in ['aliases', 'produced_from', 'source_experiments']:
continue
field_type = get_f_type(field, fields2types)
msg = validate_field(field_data, field_type, aliases_by_type, connection)
if msg:
report.append(msg)
return report
def build_patch_json(fields, fields2types):
"""Create the data entry dictionary from the fields."""
patch_data = {}
for field, field_data in fields.items():
# ignore commented out rows
if field.startswith('#'):
continue
field_type = get_f_type(field, fields2types)
patch_field = build_field(field, field_data, field_type)
if patch_field is not None:
if is_embedded_field(field):
top_field = get_field_name(field)
if patch_data.get(top_field, None) is None:
# initially create an empty list for embedded field
patch_data[top_field] = []
# we can have multiple embedded objects (they are numbered in excel)
subobject_num = get_sub_field_number(field)
if subobject_num >= len(patch_data[top_field]):
# add a new row to the list
patch_data[top_field].append(patch_field)
else:
# update existing object in the list
patch_data[top_field][subobject_num].update(patch_field)
else:
# normal case, just update the dictionary
patch_data.update(patch_field)
return patch_data
def get_just_filename(path):
return pp.Path(path).name
def check_extra_file_meta(ef_info, seen_formats, existing_formats):
try:
ef_format = ef_info.get('file_format')
except AttributeError:
print('WARNING! -- Malformed extrafile field formatting', ef_info)
return None, seen_formats
else:
if not ef_format:
return ef_info, seen_formats
# convert format to @id
ef_format = '/file-formats/' + ef_format + '/'
ef_info['file_format'] = ef_format
if ef_format in existing_formats:
print("An extrafile with %s format exists - will attempt to patch" % ef_format)
filepath = ef_info.get('filename')
if filepath is not None:
sfilename = get_just_filename(filepath)
ef_info['submitted_filename'] = sfilename
if not ef_info.get('md5sum'):
ef_info['md5sum'] = md5(filepath)
if not ef_info.get('filesize'):
ef_info['filesize'] = pp.Path(filepath).stat().st_size
seen_formats.append(ef_format)
return ef_info, seen_formats
def populate_post_json(post_json, connection, sheet, attach_fields): # , existing_data):
"""Get existing, add attachment, check for file and fix attribution."""
# add attachments
for af in attach_fields:
if post_json.get(af):
attach = attachment(post_json[af])
post_json[af] = attach
existing_data = get_existing(post_json, connection)
# Combine aliases
if post_json.get('aliases') != ['*delete*']:
if post_json.get('aliases') and existing_data.get('aliases'):
aliases_to_post = list(set(filter(None, post_json.get('aliases') + existing_data.get('aliases'))))
post_json["aliases"] = aliases_to_post
# Combine tags
if post_json.get('tags') != ['*delete*']:
if post_json.get('tags') and existing_data.get('tags'):
tags_to_post = list(set(filter(None, post_json.get('tags') + existing_data.get('tags'))))
post_json["tags"] = tags_to_post
# delete calculated property
if post_json.get('@id'):
del post_json['@id']
# should I upload files as well?
file_to_upload = False
filename_to_post = post_json.get('filename')
if filename_to_post:
# remove full path from filename
just_filename = get_just_filename(filename_to_post)
# if new file
if not existing_data.get('uuid'):
post_json['filename'] = just_filename
file_to_upload = True
# if there is an existing file metadata, the status should be uploading to upload a new one
elif existing_data.get('status') in ['uploading', 'upload failed']:
post_json['filename'] = just_filename
file_to_upload = True
else:
# if not uploading a file, do not post the filename
del post_json['filename']
# deal with extrafiles
extrafiles = post_json.get('extra_files')
extrafiles2upload = {}
if extrafiles:
# in sheet these will be file paths need to both poopulate the extrafiles properties
# in post or patch as well as upload the file if not already there
existing_formats = []
existing_extrafiles = []
extrafile_metadata = []
if existing_data:
if existing_data.get('extra_files'):
existing_extrafiles = existing_data.get('extra_files') # to include existing
existing_formats = [ef.get('file_format') for ef in existing_data.get('extra_files')]
seen_formats = []
for extrafile in extrafiles:
extrafile_meta, seen_formats = check_extra_file_meta(extrafile, seen_formats, existing_formats)
if extrafile_meta:
if extrafile_meta.get('file_format'):
if extrafile_meta.get('filename'):
extrafiles2upload[extrafile_meta['file_format']] = extrafile_meta['filename']
del extrafile_meta['filename']
for ix, eef in enumerate(existing_extrafiles):
if eef['file_format'] == extrafile_meta['file_format']:
# we are patching so want to remove existing entry from existing_extrafiles
del existing_extrafiles[ix]
break
extrafile_metadata.append(extrafile_meta)
if extrafile_metadata:
# we have data to update
post_json['extra_files'] = extrafile_metadata + existing_extrafiles
else:
del post_json['extra_files']
# if no existing data (new item), add missing award/lab information from submitter
if not existing_data.get("award"):
post_json = fix_attribution(sheet, post_json, connection)
return post_json, existing_data, file_to_upload, extrafiles2upload
def filter_set_from_exps(post_json):
"""Experiments set information is taken from experiments and submitted to experiment_set."""
rep_set_info = []
exp_set_info = []
# Part I - Replicate Sets
# store the values in a list and delete them from post_json
if post_json.get('replicate_set'):
for replicate_field in ['replicate_set', 'bio_rep_no', 'tec_rep_no']:
rep_set_info.append(post_json[replicate_field])
post_json.pop(replicate_field)
# Part II - Experiment Sets
if post_json.get('experiment_set'):
exp_set_info.append(post_json['experiment_set'])
post_json.pop('experiment_set')
return post_json, rep_set_info, exp_set_info
def filter_loadxl_fields(post_json, sheet):
"""All fields from the list_of_loadxl_fields are taken out of post_json and accumulated in dictionary."""
patch_loadxl_item = {}
for sheet_loadxl, fields_loadxl in list_of_loadxl_fields:
if sheet == sheet_loadxl:
for field_loadxl in fields_loadxl:
if post_json.get(field_loadxl):
patch_loadxl_item[field_loadxl] = post_json[field_loadxl]
del post_json[field_loadxl]
return post_json, patch_loadxl_item
def combine_set(post_json, existing_data, sheet, accumulate_dict):
"""Combine experiment related information form dictionaries with existing information."""
# find all identifiers from exisiting set item to match the one used in experiments sheet
identifiers = []
for identifier in ['accession', 'uuid', 'aliases', '@id']:
ex_item_id = existing_data.get(identifier, '')
item_id = post_json.get(identifier, ex_item_id)
# to extract alias from list
if isinstance(item_id, list) and item_id:
item_id = item_id[0]
if item_id:
identifiers.append(item_id)
# search dictionary for the existing item id
for identifier in identifiers:
if accumulate_dict.get(identifier):
add_to_post = accumulate_dict.get(identifier)
# Combination for experimentsets
if sheet == "ExperimentSet":
if existing_data.get('experiments_in_set'):
existing_exps = existing_data.get('experiments_in_set')
post_json['experiments_in_set'] = list(set(add_to_post + existing_exps))
else:
post_json['experiments_in_set'] = add_to_post
# Combination for replicate sets
if sheet == "ExperimentSetReplicate":
if existing_data.get('replicate_exps'):
existing_sets = existing_data.get('replicate_exps')
new_exps = [i['replicate_exp'] for i in add_to_post]
existing_sets = [i for i in existing_sets if i['replicate_exp'] not in new_exps]
post_json['replicate_exps'] = add_to_post + existing_sets
else:
post_json['replicate_exps'] = add_to_post
# remove found item from the accumulate_dict
accumulate_dict.pop(identifier)
return post_json, accumulate_dict
def error_report(error_dic, sheet, all_aliases, connection, error_id=''):
"""From the validation error report, forms a readable statement."""
# This dictionary is the common elements in the error dictionary I see so far
# I want to catch anything that does not follow this to catch different cases
error_header = {'@type': ['ValidationFailure', 'Error'], 'code': 422, 'status': 'error',
'title': 'Unprocessable Entity', 'description': 'Failed validation'}
report = []
if all(item in error_dic.items() for item in error_header.items()):
for err in error_dic['errors']:
error_description = err['description']
# if no field specified in the error, schema wide error
if not err['name']:
report.append("{sheet:<30}{des}"
.format(des=error_description, sheet="ERROR " + sheet.lower()))
else:
# field errors
if error_description[-9:] == 'not found':
# if error is about object connections, check all aliases
# ignore ones about existing aliases
not_found = error_description[1:-11]
if not_found in all_aliases:
continue
error_field = err['name']
report.append("{sheet:<30}Field '{er}': {des}"
.format(er=error_field, des=error_description, sheet="ERROR " + sheet.lower()))
# if there is a an access forbidden error
elif error_dic.get('title') == 'Forbidden':
error_description = error_dic['description']
try:
report.append("{sheet:<30}{eid}: {des}"
.format(des=error_description, eid=error_id, sheet="ERROR " + sheet.lower()))
except Exception:
return error_dic
# if there is a conflict
elif error_dic.get('title') == "Conflict":
try:
report.extend(conflict_error_report(error_dic, sheet, connection))
except Exception:
return error_dic
# if nothing works, give the full error, we should add that case to our reporting
else:
return error_dic
if report:
report_print = '\n'.join(report)
return report_print
else:
# if report is empty, return False
return
def conflict_error_report(error_dic, sheet, connection):
# I am not sure of the complete case of HTTPConflicts
# To make sure we get all cases reported, I put a try/except
all_conflicts = []
try:
# list is reported as string, turned into list again
conflict_str = error_dic.get('detail').replace("Keys conflict:", "").strip()
conflict_list = ast.literal_eval(conflict_str)
for conflict in conflict_list:
error_field = conflict[0].split(":")[1]
error_value = conflict[1]
try:
# let's see if the user has access to conflicting item
search = "search/?type={sheet}&{field}={value}".format(sheet=sheet,
field=error_field,
value=error_value)
existing_item = ff_utils.search_metadata(search, key=connection.key)
at_id = existing_item.get('@id')
add_text = "please use " + at_id
except Exception:
# if there is a conflicting item, but it is not viewable by the user,
# we should release the item to the project/public
add_text = "please contact DCIC"
conflict_rep = ("{sheet:<30}Field '{er}': '{des}' already exists, {at}"
.format(er=error_field, des=error_value, sheet="ERROR " + sheet.lower(), at=add_text))
all_conflicts.append(conflict_rep)
return all_conflicts
except Exception:
return
def update_item(verb, file_to_upload, post_json, filename_to_post, extrafiles, connection, identifier):
if file_to_upload and not post_json.get('md5sum'):
print("calculating md5 sum for file %s " % (filename_to_post))
post_json['md5sum'] = md5(filename_to_post)
try:
if verb == 'PATCH':
e = ff_utils.patch_metadata(post_json, identifier, key=connection.key)
elif verb == 'POST':
e = ff_utils.post_metadata(post_json, identifier, key=connection.key)
else:
raise ValueError('Unrecognized verb - must be POST or PATCH')
except Exception as problem:
e = parse_exception(problem)
if e.get('status') == 'error':
return e
if file_to_upload:
# get s3 credentials
if verb == 'PATCH':
creds = get_upload_creds(e['@graph'][0]['accession'], connection)
e['@graph'][0]['upload_credentials'] = creds
# upload
upload_file_item(e, filename_to_post)
if extrafiles:
extcreds = e['@graph'][0].get('extra_files_creds')
for fformat, filepath in extrafiles.items():
try:
file_format = ff_utils.get_metadata(fformat, key=connection.key)
ff_uuid = file_format.get('uuid')
except Exception:
raise "Can't find file_format item for %s" % fformat
for ecred in extcreds:
if ff_uuid == ecred.get('file_format'):
upload_creds = ecred.get('upload_credentials')
upload_extra_file(upload_creds, filepath)
return e
def patch_item(file_to_upload, post_json, filename_to_post, extrafiles, connection, existing_data):
return update_item('PATCH', file_to_upload, post_json, filename_to_post,
extrafiles, connection, existing_data.get('uuid'))
def post_item(file_to_upload, post_json, filename_to_post, extrafiles, connection, sheet):
return update_item('POST', file_to_upload, post_json, filename_to_post, extrafiles, connection, sheet)
def delete_fields(post_json, connection, existing_data):
"""Deletes fields with the value '*delete*'."""
# find fields to be removed
fields_to_be_removed = []
for key, value in post_json.items():
if value in ['*delete*', ['*delete*']]:
fields_to_be_removed.append(key)
# if there are no delete fields, move along sir
if not fields_to_be_removed:
return post_json
# Use the url argument delete_fields for deletion
del_add_on = 'delete_fields=' + ','.join(fields_to_be_removed)
ff_utils.patch_metadata({}, existing_data["uuid"], key=connection.key, add_on=del_add_on)
# Remove them also from the post_json
for rm_key in fields_to_be_removed:
del post_json[rm_key]
return post_json
def remove_deleted(post_json):
"""Removes fields that have *delete* keyword,
used for Post and Validation."""
fields_to_be_removed = []
for key, value in post_json.items():
if value in ['*delete*', ['*delete*']]:
fields_to_be_removed.append(key)
for rm_key in fields_to_be_removed:
del post_json[rm_key]
return post_json
def _add_e_to_edict(alias, err, errors):
if alias in errors:
if err not in errors[alias]:
errors[alias].append(err)
else:
errors[alias] = [err]
return errors
def _pairing_consistency_check(files, errors):
"""checks the datastructure for consistency"""
file_list = sorted([f for f in files if not files[f].get('symlink')])
pair_list = []
for f, info in files.items():
# skip links for secondary aliases