-
Notifications
You must be signed in to change notification settings - Fork 6
/
data-build.py
executable file
·2237 lines (1969 loc) · 80.6 KB
/
data-build.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
# This software is Copyright (C) 2018 The Regents of the University of
# California. All Rights Reserved. Permission to copy, modify, and
# distribute this software and its documentation for educational, research
# and non-profit purposes, without fee, and without a written agreement is
# hereby granted, provided that the above copyright notice, this paragraph
# and the following three paragraphs appear in all copies. Permission to
# make commercial use of this software may be obtained by contacting:
#
# Office of Innovation and Commercialization
#
# 9500 Gilman Drive, Mail Code 0910
#
# University of California
#
# La Jolla, CA 92093-0910
#
# (858) 534-5815
#
#
# This software program and documentation are copyrighted by The Regents of
# the University of California. The software program and documentation are
# supplied "as is", without any accompanying services from The Regents. The
# Regents does not warrant that the operation of the program will be
# uninterrupted or error-free. The end-user understands that the program
# was developed for research purposes and is advised not to rely
# exclusively on the program for any reason.
#
# IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
# INCLUDING LOST PR OFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
# DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY
# DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
# SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
# CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
# ENHANCEMENTS, OR MODIFICATIONS.
#
__author__ = "Bradley Huffaker"
__email__ = "<[email protected]>"
import json
import sys
import os
import re
import time
import datetime
import argparse
import subprocess
import lib.utils as utils
import unidecode
import csv
import copy
import binascii
######################################################################
## Parameters
######################################################################
import argparse
parser = argparse.ArgumentParser(description='Collections metadata of bgpstream users')
parser.add_argument('-s', '--summary', dest='summary_file', help='Summary file to read additional metadata in', required=True)
parser.add_argument('-r', '--redirects', dest='redirects_file', help='lists of redirects')
parser.add_argument("-i", dest="ids_file", help="ids_file", type=str)
parser.add_argument("-c", dest="schema_category_file", help="data schema categories", type=str)
parser.add_argument("-d", dest="schema_dataset_file", help="data schema datasets", type=str)
parser.add_argument("-D", dest="git_dates_skip", help="doesn't add dates, faster", action='store_true')
parser.add_argument("-R", dest="readable_output", help="indents the output to make it readaable", action='store_true')
args = parser.parse_args()
# used to plural
import nltk
#if not args.dates_skip:
# nltk.download('wordnet')
#nltk.download('omw-1.4')
from nltk.stem.wordnet import WordNetLemmatizer
Lem = WordNetLemmatizer()
source_dir="sources"
id_info = {}
id_object = {}
id_paper = {}
id_id_link = {}
organization_ids = {}
# Score weights
# The score encodes that the word exist at a given level.
WORD_SCORE_WEIGHT = {
"name":32,
"id":16,
"category":8,
"tags":4,
"other":2,
"link":1
}
WORD_SCORE_WEIGHT_LINK = WORD_SCORE_WEIGHT["link"]
id_word_score = {}
personName_ids = {}
type_ids = {}
singular_plural = {}
re_tag = re.compile("^tag:")
re_only_white_space = re.compile("^\s*$")
#re_not_word = re.compile("[\s ,\?\.\(\)\:]+")
re_not_word = re.compile("[^a-z^A-Z^0-9]+")
re_word = re.compile("^[a-zA-Z0-9]+$",re.IGNORECASE)
re_html = re.compile("<[^>]+>")
re_id_illegal = re.compile("[^a-z^\d^A-Z]+")
re_type_name = re.compile("([^\:]+):(.+)")
re_readme_md = re.compile("^readme\.md$",re.IGNORECASE)
re_date_key = re.compile("^date",re.IGNORECASE)
re_not_digit = re.compile("[^\d]+")
re_placeholder = re.compile("___")
repo_url_default = "https://github.com/CAIDA/catalog-data"
# Weight used to create id scoring for search
# currently not used.
# id_score_node_weight = 20
# id_score_link_weight = .2
id_object_file = "id_object.json"
id_id_link_file = "id_id_link.json"
word_id_score_file = "word_id_score.json"
id_words_file = "id_words.json"
access_word_id_file = "access_word_id.json"
status_word_id_file = "status_word_id.json"
organization_ids_file = "organization_ids.json"
personName_ids_file = "personName_ids.json"
type_ids_file = "type_ids.json"
# We will be scoring based on the depth
category_id_score_file = "category_id_score.json"
pubdb_links_file = "data/pubdb_links.json"
filename_errors = {}
# Weights used to create word scoring for search
weight_default = 1
temp="""
key_weight = {
"__typename":0,
"id":0,
"name": 10,
"nameFirst": 10,
"nameLast": 10,
"tags": 10,
"description": 5,
"content": 3,
"authors": 3
}
link_weight = {
"Paper":.3,
"Dataset":.5,
"Software":.3,
"Recipe":.3
}
type_key_w_type_w = {
"datasets": {
"key_weights": [
["name", 10],
["description",1],
["tags",.5]
],
"link_weights":[
["papers",.5],
]
},
"papers": {
"key_weights": [
["name", 10],
["description",8]
],
"type_weights":[
["tags",.5],
["datasets", .5]
]
}
}
"""
##################################
# Enumrated types
##################################
enum_type_key_values = {
"_all_":{
"visibility":["public","links","hidden","private"],
},
"Software":{
"status":["supported","unsupported","deprecated"]
}
}
if len(sys.argv) > 1 and sys.argv[1] == "-f":
date_lookup_force = True
else:
date_lookup_force = False
# id_in_catalog stores the ids that are in catalog
# used if the catalog-data-caida directory is not here
id_in_catalog = set()
################################
# Category to Object Map
################################
category_object = {}
def main():
# Load ids from the catalog
if args.ids_file:
with open(args.ids_file) as fin:
for line in fin:
id_in_catalog.add(line.rstrip())
id_date_load(id_object_file)
# valid object types
object_types = set([
"dataset",
"license",
"person",
"paper",
"presentation",
"software",
"media",
"collection",
"venue",
"category"
])
#######################
#######################
seen_id = {}
print ("----")
#Goes through all generated objects in source paths
for fname in sorted(os.listdir(source_dir)):
path = source_dir+"/"+fname
if fname == "solution" or fname == "recipe":
obj = recipe_process(path)
elif fname in object_types:
print ("loading",path)
type_ = fname
for filename in sorted(os.listdir(path)):
if re.search("\.json$",filename,re.IGNORECASE) or re.search("\.md$", filename,re.IGNORECASE):
try:
pname = path+"/"+filename
if re.search("\.json$",filename,re.IGNORECASE):
info = json.load(open(pname))
else:
info = utils.parse_markdown(pname);
if "filename" not in info:
info["filename"] = path+"/"+filename
obj = object_add(type_,info)
id = obj["id"]
if id in seen_id:
utils.warning_add(filename, "duplicate id found in\n "+ seen_id[id])
else:
seen_id[id] = filename
if "name" not in obj or obj["name"] == "":
utils.error_add(filename, "no name in oject")
if obj is None:
print ("parse error ",path+"/"+filename)
except Exception as e:
print ("\nerror",path+"/"+filename)
print (" ",e)
sys.exit(1)
else:
obj = None
print ("processing obj")
object_finished = set()
for obj in list(id_object.values()):
id_ = obj["id"]
if id_ not in object_finished:
object_finish(obj)
object_finished.add(id_)
#if obj["__typename"] == "License":
#print (obj["id"]," ",obj["__typename"])
#if id_ == "license:caida_aua":
#print (json.dumps(obj,indent=4))
if args.git_dates_skip:
print ("not checking git dates")
print ("adding dates ( skipping '*___*' )")
for obj in list(id_object.values()):
object_date_add(args.git_dates_skip, obj)
print ("removing missing ids from id_id_links")
missing = []
for id0,id_link in id_id_link.items():
if id0 not in id_object:
missing.append(id0)
else:
m = []
for id1 in id_link.keys():
if id1 not in id_object:
m.append(id1)
for id1 in m:
del id_link[id1]
if len(missing) > 0:
utils.warning_add(f"Missing {len(missing)} ids:", f"{', '.join(str(x) for x in missing)}")
for id0 in missing:
del id_id_link[id0]
######################
# tag objects linked to caida_data
######################
tag_caida_data = "tag:used_caida_data"
tag_obj = id_object[tag_caida_data] = {"__typename":"Tag", "id":"tag:used_caida_data", "name":"used CAIDA data", "filename":sys.argv[0]}
used_caida_data_link_labels = ["used by", "used to create", "usedBy", "uses", "isDerivedFrom"] # link labels that will be considered as using caida data
ids = set()
for id0,id_link in id_id_link.items():
obj0 = id_object[id0]
# Checks that the linked object is a CAIDA dataset
if obj0["__typename"] == "Dataset" and "tag:caida" in obj0["tags"]:
for id1, id_link_value1 in id_link.items():
obj1 = id_object[id1]
# get label of link
is_used_caida_data = True # boolean to track if the link should be considered as "using caida data"
if 'label' in id_link_value1:
link_label = id_link_value1["label"]
# based on label, decide if the tag should be added
if link_label not in used_caida_data_link_labels:
is_used_caida_data = False
# correctly check and then add ids that need new tag used_caida_data
if obj1["__typename"] != "Tag" and "tag:caida_data" not in obj1["tags"] and is_used_caida_data:
if "tags" not in obj1:
obj1["tags"] = []
ids.add(obj1["id"])
if tag_caida_data not in obj1["tags"]:
obj1["tags"].append(tag_caida_data)
######################
link = {"to":tag_caida_data}
for id_ in ids:
link_add(id_object[id_], link)
#######################
# Check that the objects are valid
#######################
type_checker = {
"Person":person_add_names,
"Dataset":object_checker,
"Software":object_checker,
"Paper":object_checker,
"Media":object_checker
}
id_failed = []
# Loop through the names in the id_object json file
for id_,obj in id_object.items():
type_ = obj["__typename"]
if type_ in type_checker:
## I think it is here where the object gets person add names again
type_checker[type_](obj)
#if message is not None:
# id_failed.append({"id":id_,"message":message})
for id_msg in id_failed:
id_ = id_msg["id"]
msg = id_msg["message"]
print ("removing[",msg,"]",id_)
del id_object[id_]
#######################
# Remove keys with None values
#######################
print ("removing keys with none values")
for obj in id_object.values():
remove_keys_with_none_value(obj["filename"], None,obj)
#######################
# checking if collection members are missing
#######################
print ("checking collection members ids")
for obj in id_object.values():
if obj["__typename"] == "Collection" and "members" in obj:
ids = []
for id_ in obj["members"]:
if id_ in id_object:
ids.append(id_)
else:
utils.error_add(obj["filename"], obj["id"]+"'s member "+id_+" not found")
####################
# Add in any redirects (id_old -> id_new)
# These will all be hidden, ie not searchable
####################
if args.redirects_file:
print ("adding redirects:",args.redirects_file)
redirects_add(args.redirects_file)
########################
## duplicate slide resources
########################
#print ("duplicating slides into paper access")
#duplicate_slides_in_access()
#######################
# Match up Papers with exact name media and presentation that match
#######################
print ("Matching up Papers with media/presentations with the same name")
papers_access_add_same_name()
#######################
# pubdb links
#######################
if os.path.exists(pubdb_links_file):
print ("loading",pubdb_links_file)
pub_links_load(pubdb_links_file)
else:
print("failed to file",pubdb_links_file)
print(" type 'make links'")
#######################
# count none_tab_links
#######################
for id, obj in id_object.items():
num_links = 0
if id in id_id_link:
for i in id_id_link[id].keys():
if id_object[i]["__typename"] != "Tag":
num_links += 1
id_object[id]["num_links_not_tag"] = num_links
######################
# Load date info into id_object
######################
print ("Adding dataset date info")
data_load_from_summary(args.summary_file)
# Class copies categories to classes
class_copy_from_category_keys(id_object.values())
######################
# Parse out the access words and status of datasets
######################
access_word_ids = {}
status_word_ids = {}
for obj in id_object.values():
if "access" in obj:
for access in obj["access"]:
if "access" in access:
word = access["access"]
else:
word = access["url"]
if word not in access_word_ids:
access_word_ids[word] = []
access_word_ids[word].append(obj["id"])
if "status" in obj:
curr_status = obj["status"]
if curr_status not in status_word_ids:
status_word_ids[curr_status] = []
status_word_ids[curr_status].append(obj["id"])
######################
# Load data schema for categories from file
######################
print ("Adding schema's categories from",args.schema_category_file)
schema_load_category_from_file(args.schema_category_file)
####################
print ("Build Category Object map")
category_object_build()
######################
# Load data schema for datasets from file
######################
print ("Adding schemas from",args.schema_dataset_file)
schema_load_datasets_from_file(args.schema_dataset_file)
#######################
# set up category depths
#######################
print ("processing categories")
category_id_score = schema_process()
#######################
# parse out the words from the fields
#######################
print ("adding words")
for obj in id_object.values():
word_scoring(obj)
for id0, id1_link in id_id_link.items():
if id0 not in id_word_score:
id_word_score[id0] = {}
w_s0 = id_word_score[id0]
for id1 in id1_link.keys():
if id0 < id1:
w_s1 = id_word_score[id1]
word_scoring_link(w_s0, w_s1)
word_scoring_link(w_s1, w_s0)
# Add in alternative plural/singlar
print ("adding plural")
word_add_plurals()
word_id_score = {}
for id_,word_score in id_word_score.items():
for word,score in word_score.items():
if word not in word_id_score:
word_id_score[word] = {}
word_id_score[word][id_] = score;
#######################
# Remove empty arrays
#######################
print ("removing empty obj arrays")
for obj in id_object.values():
keys = []
for key, value in obj.items():
if list == type(value) and len(value) == 0:
keys.append(key)
for key in keys:
del obj[key];
######################
# Convert set to list
######################
for name,obj in personName_ids.items():
personName_ids[name] = list(obj)
######################
# Create a type index
######################
type_ids = {}
for obj in id_object.values():
t = obj["__typename"]
if t not in type_ids:
type_ids[t] = []
type_ids[t].append(obj["id"])
######################
# Create a word_id
######################
id_words = {}
for word, id_score in word_id_score.items():
for i in id_score.keys():
if i not in id_words:
id_words[i] = set()
id_words[i].add(word)
for i,words in id_words.items():
id_words[i] = list(words)
#######################
# check dataset status
#######################
for obj in id_object.values():
for t in ["_all_", obj["__typename"]]:
if t in enum_type_key_values:
for key,valid_values in enum_type_key_values[t].items():
if key in obj and obj[key] not in valid_values:
utils.error_add(obj["filename"], f"{obj['id']}'s {key}'s \"{obj[key]}\" not in {', '.join(valid_values)}")
del obj[key]
#######################
# copy out doi && pull out access tag to access type
#######################
print ("Pulling DOIs out of access && pull out access tag to access type")
count_access_no_tags = 0
for obj in id_object.values():
doi_set(obj)
count_access_no_tags += access_type_from_tag_set(obj)
if count_access_no_tags > 0:
utils.error_add("", '%s Objects that are missing a tags and type; please add a type to each access object.' % count_access_no_tags)
#######################
# printing errors
#######################
utils.error_print()
#######################
# print files
#######################
if args.readable_output:
indent = 4
else:
indent = None
print ("writing",id_object_file)
json.dump(id_object, open(id_object_file,"w"),indent=indent)
print ("writing",personName_ids_file)
json.dump(personName_ids, open(personName_ids_file,"w"),indent=indent)
print ("writing",type_ids_file)
json.dump(type_ids, open(type_ids_file,"w"),indent=indent)
print ("writing",id_id_link_file)
json.dump(id_id_link, open(id_id_link_file,"w"),indent=indent)
print ("writing",id_words_file)
json.dump(id_words, open(id_words_file,"w"),indent=indent)
print ("writing",word_id_score_file)
json.dump(word_id_score, open(word_id_score_file,"w"),indent=indent)
print ("writing",access_word_id_file)
json.dump(access_word_ids, open(access_word_id_file,"w"),indent=indent)
print ("writing",status_word_id_file)
json.dump(status_word_ids, open(status_word_id_file,"w"),indent=indent)
print ("writing",category_id_score_file)
json.dump(category_id_score, open(category_id_score_file,"w"),indent=indent)
#################
for org,ids in organization_ids.items():
organization_ids[org] = list(ids)
print ("writing",organization_ids_file)
json.dump(organization_ids, open(organization_ids_file,"w"),indent=indent)
###########################
# Date
###########################
mon_index={"jan":"01","feb":"02","mar":"03","apr":"04","may":"05","jun":"06"
,"jul":"07","aug":"08","sep":"09","oct":"10","nov":"11","dec":"12"}
id_date = {}
def id_date_load(filename):
global id_date
if os.path.exists(filename):
try:
id_date = json.load(open(filename,"r"))
except ValueError as e:
utils.error_add(filename, e.__str__())
def object_date_add(git_dates_skip, obj):
# Created and modified
if not git_dates_skip:
## Get github file modified dates
for key in ["dateObjectCreated", "dateObjectModified"]:
if not date_lookup_force and obj["id"] in id_date and key in id_date[obj["id"]]:
obj[key] = utils.date_parse(id_date[obj["id"]][key])
else:
# if the file is not a placeholder
if not re_placeholder.search(obj["filename"]):
if key == "dateObjectCreated":
cmd = "git log --diff-filter=A --follow --format=%aD -1 -- "
else:
cmd = "git log --format=%aD -1 -- "
result = subprocess.check_output(cmd+" "+obj["filename"],shell=True)
values = result.decode().lower().split(" ")
else:
values = []
today = datetime.date.today().strftime("%Y-%m")
date = today
# if there was a date found, use as date (would not be found if placeholder)
if len(values) >= 4:
if values[2] in mon_index:
date = utils.date_parse(values[3]+"-"+mon_index[values[2]])
obj[key] = date
if obj["id"] not in id_date:
id_date[obj["id"]] = {}
# use the date if it's already defined
if "date" in obj:
return
today = datetime.date.today().strftime("%Y-%m")
if obj["__typename"] == "Venue":
if "dates" in obj and len(obj['dates']) >= 1:
for date_url in obj["dates"]:
if "date" not in obj or obj["date"] < date_url["date"]:
obj["date"] = utils.date_parse(date_url["date"])
else:
if "date" not in obj:
if "deprecated" not in obj:
utils.error_add(obj["filename"], "missing date(s), please add date(s)")
else:
for key, value in obj.items():
if key[:4] == "date" and type(value) == str:
if obj[key].lower() == "ongoing":
obj[key] = today
else:
obj[key] = utils.date_parse(obj[key])
# change date start to dateCreated for software
#if obj["__typename"] == "Software":
# if "dateCreated" not in obj and "dateModified" not in obj:
# if "deprecated" in obj:
# utils.warning_add(obj["filename"], "missing dateCreated and dateModified, but is deprecated")
# else:
# utils.error_add(obj["filename"], "missing dateCreated and dateModified, please add dateCreated or dateModified")
if "presenters" in obj:
for person_venue in obj["presenters"]:
if "date" in person_venue:
obj["date"] = utils.date_parse(person_venue["date"])
if "date" not in obj:
if "deprecated" not in obj:
utils.error_add(obj["filename"], "missing date, please add date")
else:
if "date" not in obj:
obj["date"] = None
type_key = {
"Dataset":["dateEnd", "dateStart"],
"Paper":["datePublished"],
"Software":["dateCreated","dateModified"],
"Recipe":["dateObjectModified","dateObjectCreated"],
"Tag":["dateObjectModified","dateObjectCreated"],
"Collection":["dateObjectModified", "dateObjectCreated"]
}
type_ = obj["__typename"]
if type_ in type_key:
for key in type_key[type_]:
if key in obj:
obj["date"] = obj[key]
break
if obj["date"] is None:
if "deprecated" not in obj:
utils.warning_add(obj["filename"], "missing " + ", ".join(type_key[type_]) + ", please add " + ", ".join(type_key[type_]))
#for dst,src in [["dateCreated","dateObjectCreated"], ["dateLastModified","dateObjectModified"]]:
# if dst not in obj:
# obj[dst] = obj[src]
#if obj["__typename"] == "Dataset":
#if "dateStart" in obj:
#obj["date"] = obj["dateStart"]
#else:
#utils.warning_add(obj["filename"],"dataset requires dateStart")
#obj.pop("date",None)
#else:
#if "date" not in obj:
#obj["date"] = obj["dateLastUpdated"]
#obj["date"] = utils.date_parse(obj["date"])
###########################
def data_print():
for type,data in type_data.items():
fname = data_dir+"/"+type+".json"
print ("writing",fname)
with open (fname,"w") as f:
objects = []
for object in data.values():
objects.append(object)
f.write(json.dumps(objects,indent=4, sort_keys=True))
fname = data_dir+"/id_"+type+".json"
print ("writing",fname)
with open (fname,"w") as f:
f.write(json.dumps(data,indent=4, sort_keys=True))
#############################
def remove_keys_with_none_value(filename, path, obj):
t = type(obj)
if t == dict:
iter_ = obj.items()
elif t == list:
iter_ = enumerate(obj)
else:
iter_ = None
if iter_ is not None:
nones = []
nested = []
for key, value in iter_:
if path is None:
path_key = key
else:
if t == dict:
path_key = path+"->"+key
else:
path_key = path+"["+str(key)+"]"
if value is None:
nones.append([path_key, key])
elif type(value) is dict or type(value) is list:
nested.append([path_key, value])
for path_key, key in nones:
if path_key is not None and path_key != "date":
utils.warning_add(filename, "none value for "+path_key)
if t == dict:
del obj[key]
else:
del obj[key:key+1]
for path_key,child in nested:
remove_keys_with_none_value(filename, path_key, child)
#############################
def object_add(type_, info):
info["__typename"] = type_ = type_.title()
error = False
if type_ == "Person":
person_add_names(info)
if "name" in info:
info["__typename"] = type_.title()
if "id" not in info:
info["id"] = utils.id_create(info["filename"], info["__typename"],info["name"])
else:
info["id"] = utils.id_create(info["filename"], info["__typename"],info["id"])
else:
utils.error_add(info["filename"], "failed to find name:"+json.dumps(info))
error = True
if type_ == "Paper":
if "datePublished" in info:
info["date"] = info["datePublished"]
else:
utils.error_add(info["filename"], "failed to find paper's date")
error = True
m = re.search("^paper:(\d\d\d\d)_(.+)", info["id"])
if m:
date,id_short = m.groups()
id_paper[id_short] = info
else:
info["id"] = utils.id_create(info["filename"], info["__typename"],info["id"])
elif type_ == "Category":
if "id_short" not in info:
info["id_short"] = info["id"]
if "category_keys" in info:
for cat in info["category_keys"]:
if "id_short" not in cat:
cat["id_short"] = cat["id"]
if not error:
id_object[info["id"]] = info
if "id_short" in info:
id_short = utils.id_create(info["filename"], info["__typename"], info["id_short"])
if id_short != info["id"]:
if id_short not in id_object:
id_object[id_short] = info
else:
utils.error_add(info["filename"], f'{id_object["id"]}\'s id_short "{id_short}" already used')
del info["id_short"]
elif type_ == "category":
info["id_short"] = info["id"]
return info
print("line 611, error in object add for ", info["id"])
return None
# Helper function
re_third_party = re.compile("third party",re.IGNORECASE)
third_party_found = False
def organization_ids_add(org, id_):
if re_third_party.search(id_):
if not third_party_found:
print ('ignoring organization "third party"', file=sys.stderr)
third_party_found = True
return
if org not in organization_ids:
organization_ids[org] = set()
organization_ids[org].add(id_)
re_caida = re.compile("caida",re.IGNORECASE)
re_caida_long = re.compile("Center for Applied Internet Data Analysis",re.IGNORECASE)
def object_finish(obj):
############
# links
############
if "links" in obj:
for link in obj["links"]:
link_add(obj,link)
del obj["links"]
if "tags" not in obj:
obj["tags"] = []
# Add if CAIDA is organization
is_caida = False
if "organization" in obj:
org = obj["organization"]
organization_ids_add(org, obj["id"])
if re_caida.search(org) or re_caida_long.search(org):
is_caida = True
for key in ["authors", "presenters"]:
if key in obj:
for person_org in obj[key]:
if "organizations" in person_org:
for org in person_org["organizations"]:
organization_ids_add(org, obj["id"])
if re_caida.search(org) or re_caida_long.search(org):
is_caida = True
if is_caida and "caida":
organization_ids_add("CAIDA", obj["id"])
if "caida" not in obj["tags"]:
obj["tags"].append("caida")
for key,value in obj.items():
if (key == "tags" or key == "access") and obj[key]:
objects = []
filename = obj["filename"]
if key == "tags":
objects = [obj]
else:
for i, access in enumerate(obj["access"]):
if 'access' not in access:
utils.error_add(obj["filename"], "access requires an access field")
if 'url' not in access:
utils.error_add(obj["filename"], "access requires an url field")
if "tags" in access:
objects.append(access)
for o in objects:
for i,tag in enumerate(o["tags"]):
t = object_lookup_type_name(filename, "tag",tag)
if t is not None:
tid = o["tags"][i] = t["id"]
link_add(obj,tid)
elif key == "access":
o = object_lookup_type_name(obj["filename"], "tag",tag)
if o is not None:
tag = obj["tags"][i] = o["id"]
link_add(obj,tag)
else:
utils.error_add(obj["filename"],"No object for access tag")
elif key == "resources":
for resource in value:
if "name" not in resource:
utils.error_add(obj["filename"], "resources require a name field")
#elif key == "resources":
# for resource in obj["resources"]:
# for i,tag in enumerate(resource[key]):
# resource["tags"][i] = object_lookup_type_name("tag",tag)["id"]
elif re_date_key.search(key) and type(obj[key]) == str:
date = utils.date_parse(obj[key])
if date:
obj[key] = date
#values = re_not_digit.split(obj[key])
#digits = ["1990","01","01","00","00","00"]
#for i,value in enumerate(values):
#digits[i] = value
##dt = datetime.datetime.strptime(" ".join(digits), "%Y %m %d %H %M %S")
#date = int(time.mktime(dt.timetuple()))
#obj[key] = "%s/%s/%s %s:%s:%s" % (digits[0],digits[1],digits[2],digits[3],digits[4],digits[5])
#elif obj["__typename"] == "Venue" and key == "dates":
# for date_url in obj[key]:
# venue_add_date_url(obj,date_url["date"],date_url["url"])
elif key == "persons" or key == "venues" or key == "presenters" or key == "authors":
dirty = []
i = 0
persons = set()
while i < len(obj[key]):
person_org = obj[key][i]
error = False
if type(person_org) == dict:
caida = False
if "organizations" in person_org:
for org in person_org["organizations"]:
if re.search("caida", org, re.IGNORECASE):
caida = True
for k in ["person","presenter"]:
if k in person_org:
person = person_lookup_id(obj["filename"],person_org[k])
persons.add(person["id"])
if person is not None:
if caida: