-
Notifications
You must be signed in to change notification settings - Fork 4
/
data_processing.py
1080 lines (701 loc) · 34.8 KB
/
data_processing.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
from os.path import isfile, join
from os import listdir
import nltk
import pickle
import numpy as np
import pandas as pd
import torch
from collections import OrderedDict
from torch import tensor
def get_number_segments(folder):
"""
Computes the number of segments in the files inside the folder
Args:
folder: string, path to the folder we want to examine
Returns:
number_segments: integer, number of segments inside the folder
"""
number_segments = 0
files = [join(folder, f) for f in listdir(folder) if isfile(join(folder, f))]
for f in files:
with open(f, "rb") as f_opened:
number_segments += len(pickle.load(f_opened))
return number_segments
def sentence_serialization(sentence, word2idx, lower_case = True):
"""
Transforms a sentence into a list of integers. No integer will be appended if the token is not present in word2idx.
Args:
sentence: string, sentence that we want to serialize.
word2idx: dictionary, dictionary with words as keys and indexes as values.
lower_case: boolean, turns all words in the sentence to lower case. Useful if word2idx
doesn't support upper case words.
Returns:
s_sentence: list, list containing the indexes of the words present in the sentence.
s_sentence stands for serialized sentence.
"""
s_sentence = []
not_found = 0
if lower_case:
tokens = map(str.lower,nltk.word_tokenize(sentence))
else:
tokens = nltk.word_tokenize(sentence)
for token in tokens:
try:
s_sentence.append(word2idx[token])
except KeyError:
not_found += 1
print("Warning: At least one token is not present in the word2idx dict. For instance: " + token +
". Not found: " + str(not_found))
return s_sentence
def get_tokens(inputh_path, output_path, read = False):
"""
Checks all the files in filespath and returns a set of all the words found in the files. The function will ignore all the folders inside filespath automatically.
We set all the words to be lower case. The function will check if the a file with all the tokens is available. In that case this function
will be much faster.
Args:
filespath: string, path to the folder with all the files containing the words that we want to extract.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
dictionary: set, set containing all the different words found in the files.
"""
dictionary_path = join(output_path, "dictionary.pkl")
if isfile(dictionary_path) and read:
print("Loading from file dictionary.pkl")
with open(dictionary_path,"rb") as dictionary_file:
word2idx_dictionary = pickle.load(dictionary_file)
else:
print("Processing dataset ...")
dictionary = set()
files = [join(inputh_path, f) for f in listdir(inputh_path) if isfile(join(inputh_path, f))]
files = [file for file in files if ".keep" not in file]
#files.remove(join(inputh_path,".keep"))
for f in files:
opened_file = open(f,'r')
for i, line in enumerate(opened_file):
a = line.split('","')
a[1] = map(str.lower,set(nltk.word_tokenize(a[1])))
dictionary = dictionary.union(a[1])
dictionary = sorted(dictionary)
word2idx_dictionary = {None: 0}
for i, word in enumerate(dictionary,1):
word2idx_dictionary[word] = i
with open(dictionary_path, "wb") as dictionary_file:
pickle.dump(word2idx_dictionary, dictionary_file)
return word2idx_dictionary
def get_policy_of_interest_tokens(paragraphs, output_path):
all_tokens_path = join(output_path, "policy_of_interest_tokens.pkl")
print("Processing all tokens of the policy of interest ...")
all_tokens = set()
for paragraph in paragraphs:
segment = map(str.lower, set(nltk.word_tokenize(paragraph)))
all_tokens = all_tokens.union(segment)
all_tokens = sorted(all_tokens)
word2idx_dictionary = {None: 0}
for i, word in enumerate(all_tokens, 1):
word2idx_dictionary[word] = i
with open(all_tokens_path, "wb") as dictionary_file:
pickle.dump(word2idx_dictionary, dictionary_file)
return word2idx_dictionary
def label_to_vector(label, labels, count):
"""
Returns a vector representing the label passed as an input.
Args:
label: string, label that we want to transform into a vector.
labels: dictionary, dictionary with the labels as the keys and indexes as the values.
Returns:
vector: np.array, 1-D array of lenght 12.
"""
vector = np.zeros((count))
try:
index = labels[label]
vector[index] = 1
except KeyError:
vector = np.zeros((count))
return vector
def get_glove_dicts(parent_folder, input_path, output_path, dims, read = False):
"""
This functions returns two dictionaries that process the glove.6B folder and gets the pretrained
embedding vectors.
Args:
path: string, path to the folder containing the glove embeddings
dims: integer, embeddings dimensionality to use.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
word2vector: dictionary, the keys are the words an the values are the embeddings associated with that word.
word2idx: dictionary, the keys are the words and the values are the indexes associated with that word.
"""
word2vector_path = "word2vector_globe_" + str(dims) + ".pkl"
word2vector_path = join(output_path, word2vector_path)
word2idx_path = "word2idx_globe_" + str(dims) + ".pkl"
word2idx_path = join(output_path, word2idx_path)
if isfile(word2vector_path) and read:
print("Loading from file word2vector_globe_{}.pkl".format(dims))
with open(word2vector_path,"rb") as word2vector_file:
word2vector = pickle.load(word2vector_file)
else:
print("Processing dataset ...")
words = [None]
word2idx = {None: 0}
idx = 1
vectors = [np.zeros(dims)]
with open(join(parent_folder, input_path, input_path + "." + str(dims) + "d.txt"), encoding="utf-8") as glove_file:
for line in glove_file:
split_line = line.split()
word = split_line[0]
words.append(word)
word2idx[word] = idx
vector = np.array(split_line[1:]).astype(np.float)
vectors.append(vector)
idx += 1
word2vector = {w: vectors[word2idx[w]] for w in words}
with open(word2vector_path,"wb") as word2vector_file:
pickle.dump(word2vector, word2vector_file)
return word2vector
def get_fast_text_dicts(input_path, output_path, dims, missing = True, read = False):
"""
This functions returns two dictionaries that process the fasttext folder and gets the pretrained
embedding vectors.
Args:
path: string, path to the folder containing the glove embeddings
dims: integer, embeddings dimensionality to use.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
word2vector: dictionary, the keys are the words an the values are the embeddings associated with that word.
word2idx: dictionary, the keys are the words and the values are the indexes associated with that word.
"""
def append_from_file(words, word2idx, vectors, idx, input_path, file):
with open(join(input_path, file) , encoding="utf8") as fast_text_file:
for line in fast_text_file:
"""if idx == 158090:"""
split_line = line.split()
word = split_line[0]
words.append(word)
word2idx[word] = idx
vector = np.array(split_line[1:]).astype(np.float)
vectors.append(vector)
idx += 1
return words, word2idx, vectors, idx
if missing:
word2vector_path = "word2vector_fast_text_" + str(dims) + "_nomissing.pkl"
word2vector_path = join(output_path, word2vector_path)
word2idx_path = "word2idx_fast_text_" + str(dims) + "_nomissing.pkl"
word2idx_path = join(output_path, word2idx_path)
else:
word2vector_path = "word2vector_fast_text_" + str(dims) + ".pkl"
word2vector_path = join(output_path, word2vector_path)
word2idx_path = "word2idx_fast_text_" + str(dims) + ".pkl"
word2idx_path = join(output_path, word2idx_path)
if isfile(word2vector_path) and read:
print("Loading from file {}".format(word2vector_path))
with open(word2vector_path,"rb") as word2vector_file:
word2vector = pickle.load(word2vector_file)
else:
print("Processing dataset ...")
words = [None]
word2idx = {None: 0}
idx = 1
vectors = [np.zeros(dims)]
words, word2idx, vectors, idx = append_from_file(words, word2idx, vectors, idx, input_path, '.vec')
if missing:
words, word2idx, vectors, idx = append_from_file(words, word2idx, vectors, idx, input_path, '.vec_missing')
word2vector = {w: vectors[word2idx[w]] for w in words}
with open(word2vector_path,"wb") as word2vector_file:
pickle.dump(word2vector, word2vector_file)
return word2vector
def get_weight_matrix(dims, output_path, read = False, oov_random = True, **kwargs):
"""
This function returns a matrix containing the weights that will be used as pretrained embeddings. It will read
weights_matrix.pkl file as long as it exists. This will make the code much faster.
Args:
dictionary: dictionary, dictionary containing a word2idx of all the words present in the dataset.
word2vector: dictionary, the keys are the words and the values are the embeddings.
dims: integer, dimensionality of the embeddings.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
weights_matrix: np.array, matrix containing all the embeddings.
"""
weights_path = "weights_matrix_" + str(dims) + ".pkl"
weights_path = join(output_path, weights_path)
if isfile(weights_path) and read:
print("Loading from file weights_matrix_{}.pkl".format(dims))
with open(weights_path,"rb") as weights_file:
weights_matrix = pickle.load(weights_file , encoding="latin1")
else:
print("Processing dataset ...")
# We add 1 to onclude the None value
dictionary = kwargs['dictionary']
word2vector = kwargs['word2vector']
matrix_len = len(dictionary) + 1
weights_matrix = np.zeros((matrix_len, dims))
oov_words = 0
for word, i in dictionary.items():
try:
weights_matrix[i] = word2vector[word]
except KeyError:
if oov_random:
weights_matrix[i] = np.random.normal(scale=0.6, size=(dims, ))
oov_words += 1
if oov_words != 0:
print("Some words were missing in the word2vector. {} words were not found.".format(oov_words))
with open(weights_path,"wb") as weights_file:
pickle.dump(weights_matrix, weights_file)
return weights_matrix
def process_dataset(labels, word2idx, read = False):
"""
This function process all the privacy policy files and transforms all the segments into lists of integers. It also
transforms all the labels into a list of 0s except in the positions associated with the labels in which we will find 1s
where we will find a 1. It will also place .pkl files into the processed_data folder so that we can load the data from
there instead of having to process the whole dataset.
Args:
path: string, path where all the files we want to process are located (all the privacy policies).
word2idx: dictionary the keys are the words and the values the index where we can find the vector in
weights_matrix.
labels: labels: dictionary, dictionary with the labels as the keys and indexes as the values.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
sentence_matrices: list, a list of lists of lists containing the segments of the files transformed into integers.
sentence_matrices[i][j][k] -> "i" is for the file, "j" for the line and "k" for the token.
labels_matrices: list, a list of lists of lists containing the labels of the dataset. labels_matrices[i][j][k] ->
"i" is for the file, "j" for the line and "k" for the boolean variable specifying
the presence of the a label.
"""
"""
Helper functions
"""
def pickle_matrix(matrix, path):
with open(path,"wb") as output_file:
pickle.dump(matrix, output_file)
def unpickle_matrix(path):
with open(path,"rb") as input_file:
matrix = pickle.load(input_file)
return matrix
"""
main code of process_dataset
"""
input_path = "agg_data"
output_path = "processed_data"
path_sentence_matrices = join(output_path, "all_sentence_matrices.pkl")
path_labels_matrices = join(output_path, "all_label_matrices.pkl")
if isfile(path_sentence_matrices) and isfile(path_labels_matrices) and read:
print("Loading from " + path_sentence_matrices + " and " + path_labels_matrices)
sentence_matrices = unpickle_matrix(path_sentence_matrices)
labels_matrices = unpickle_matrix(path_labels_matrices)
return sentence_matrices, labels_matrices
else:
print("Processing dataset ...")
with open("agg_data/agg_data.pkl",'rb') as dataframe_file:
opened_dataframe = pickle.load(dataframe_file)
num_records = len(opened_dataframe)
print('Num of unique segments segments: {}'.format(num_records))
num_labels = len(opened_dataframe["label"].iloc[0])
sentence_matrices = np.zeros(num_records, dtype = 'object')
labels_matrices = np.zeros((num_records, num_labels))
for index, row in opened_dataframe.iterrows():
segment = row["segment"]
label = row["label"]
sentence_matrices[index] = sentence_serialization(segment, word2idx)
labels_matrices[index] = label
path_sentence_matrices = join(output_path, "all_sentence_matrices.pkl")
path_labels_matrices = join(output_path, "all_label_matrices.pkl")
pickle_matrix(sentence_matrices, path_sentence_matrices)
pickle_matrix(labels_matrices, path_labels_matrices)
return sentence_matrices, labels_matrices
def process_policy_of_interest(word2idx , segments):
"""
This function process all the privacy policy files and transforms all the segments into lists of integers. It also
transforms all the labels into a list of 0s except in the positions associated with the labels in which we will find 1s
where we will find a 1. It will also place .pkl files into the processed_data folder so that we can load the data from
there instead of having to process the whole dataset.
Args:
path: string, path where all the files we want to process are located (all the privacy policies).
word2idx: dictionary the keys are the words and the values the index where we can find the vector in
weights_matrix.
labels: labels: dictionary, dictionary with the labels as the keys and indexes as the values.
read: boolean, variable that allows us to decide wether to read from pre-processed files or not.
Returns:
sentence_matrices: list, a list of lists of lists containing the segments of the files transformed into integers.
sentence_matrices[i][j][k] -> "i" is for the file, "j" for the line and "k" for the token.
labels_matrices: list, a list of lists of lists containing the labels of the dataset. labels_matrices[i][j][k] ->
"i" is for the file, "j" for the line and "k" for the boolean variable specifying
the presence of the a label.
"""
"""
Helper functions
"""
def pickle_matrix(matrix, path):
with open(path, "wb") as output_file:
pickle.dump(matrix, output_file)
def unpickle_matrix(path):
with open(path, "rb") as input_file:
matrix = pickle.load(input_file)
return matrix
def stack_segments(segments, clearance=2):
segments_len = map(len, segments)
max_len = max(segments_len)
segments_list = []
output_len = max_len + clearance * 2
for i, segment in enumerate(segments):
segment_array = np.array(segment)
zeros_to_prepend = int((output_len - len(segment_array)) / 2)
zeros_to_append = output_len - len(segment_array) - zeros_to_prepend
resized_array = np.append(np.zeros(zeros_to_prepend), segment_array)
resized_array = np.append(resized_array, np.zeros(zeros_to_append))
segments_list.append(torch.tensor(resized_array, dtype=torch.int64))
segments_tensor = torch.stack(segments_list).unsqueeze(1)
return segments_tensor
output_path = "processed_data"
print("Processing policy of interest ...")
num_records = len(segments)
segments_matrices = np.zeros(num_records, dtype='object')
for index in range(num_records):
segment = segments[index]
segments_matrices[index] = sentence_serialization(segment, word2idx)
path_sentence_matrices = join(output_path, "policy_of_interest_paragraphs_matrices.pkl")
pickle_matrix(segments_matrices, path_sentence_matrices)
segments_tensor = stack_segments(segments_matrices)
return segments_tensor
def collate_csv_data(word2idx ,attribute, mode, num_labels, read=False):
def stack_segments(segments, clearance=2):
segments_len = map(len, segments)
max_len = max(segments_len)
segments_list = []
output_len = max_len + clearance * 2
for i, segment in enumerate(segments):
segment_array = np.array(segment)
zeros_to_prepend = int((output_len - len(segment_array)) / 2)
zeros_to_append = output_len - len(segment_array) - zeros_to_prepend
resized_array = np.append(np.zeros(zeros_to_prepend), segment_array)
resized_array = np.append(resized_array, np.zeros(zeros_to_append))
segments_list.append(torch.tensor(resized_array, dtype=torch.int64))
segments_tensor = torch.stack(segments_list).unsqueeze(1)
return segments_tensor
print("Processing dataset ...")
attr_segment_matrices, attr_values_matrices, attr_value_tensor = process_attribute_level_testset(word2idx,attribute,mode,num_labels,read )
segments_tensor = stack_segments(attr_segment_matrices)
return segments_tensor,attr_value_tensor
def process_attribute_level_testset(word2idx ,attribute, mode, num_labels, read=False ):
def pickle_matrix(matrix, path):
with open(path, "wb") as output_file:
pickle.dump(matrix, output_file)
def unpickle_matrix(path):
with open(path, "rb") as input_file:
matrix = pickle.load(input_file)
return matrix
output_path = join("processed_data", attribute)
path_attr_segment_matrices = join(output_path, "attr_segment_matrices.pkl")
path_attr_values_matrices = join(output_path, "attr_values_matrices.pkl")
label_file = "labels_" + attribute + ".pkl"
with open(label_file, "rb") as labels_file:
labels_dict = pickle.load(labels_file)
if isfile(path_attr_segment_matrices) and isfile(path_attr_values_matrices) and read:
print("Loading from " + path_attr_segment_matrices + " and " + path_attr_values_matrices)
segment_matrices = unpickle_matrix(path_attr_segment_matrices)
labels_matrices = unpickle_matrix(path_attr_values_matrices)
return segment_matrices, labels_matrices
else:
print("Processing attribute separated data ...")
file = join('attribute_dataset', attribute + '_' + mode + '.csv')
with open(file, 'r') as opened_file:
reader = pd.read_csv(opened_file, delimiter=',', names = ["index","segment","label"])
reader['label'] = reader['label'].apply(lambda x: label_to_vector(x, labels_dict, num_labels))
num_records = len(reader['label'])
segment_matrices = np.zeros(num_records, dtype='object')
labels_matrices = np.zeros((num_records, num_labels))
for index, row in reader.iterrows():
label = row["label"]
segment = row["segment"]
segment_matrices[index] = sentence_serialization(segment, word2idx)
labels_matrices[index] = label
pickle_matrix(segment_matrices, path_attr_segment_matrices)
pickle_matrix(labels_matrices, path_attr_values_matrices)
attr_value_tensor = torch.tensor(reader['label'])
return segment_matrices, labels_matrices, attr_value_tensor
def process_attribute_level_dataset(word2idx ,attribute, mode, read=False):
"""
Helper functions
"""
def pickle_matrix(matrix, path):
with open(path, "wb") as output_file:
pickle.dump(matrix, output_file)
def unpickle_matrix(path):
with open(path, "rb") as input_file:
matrix = pickle.load(input_file)
return matrix
output_path = join("processed_data", attribute)
path_attr_segment_matrices = join(output_path, "attr_segment_matrices.pkl")
path_attr_values_matrices = join(output_path, "attr_values_matrices.pkl")
if isfile(path_attr_segment_matrices) and isfile(path_attr_values_matrices) and read:
print("Loading from " + path_attr_segment_matrices + " and " + path_attr_values_matrices)
segment_matrices = unpickle_matrix(path_attr_segment_matrices)
labels_matrices = unpickle_matrix(path_attr_values_matrices)
return segment_matrices, labels_matrices
else:
print("Processing attribute separated data ...")
file = join('agg_data', attribute + '_' + mode + '.pkl')
with open(file,'rb') as dataframe_file:
opened_dataframe = pickle.load(dataframe_file)
num_records = len(opened_dataframe)
print('Num of unique segments: {}'.format(num_records))
num_labels = len(opened_dataframe["label"].iloc[0])
segment_matrices = np.zeros(num_records, dtype = 'object')
labels_matrices = np.zeros((num_records, num_labels))
for index, row in opened_dataframe.iterrows():
segment = row["segment"]
label = row["label"]
segment_matrices[index] = sentence_serialization(segment, word2idx)
labels_matrices[index] = label
path_sentence_matrices = join(output_path, "all_sentence_matrices.pkl")
path_labels_matrices = join(output_path, "all_label_matrices.pkl")
pickle_matrix(segment_matrices, path_sentence_matrices)
pickle_matrix(labels_matrices, path_labels_matrices)
return segment_matrices, labels_matrices
def aggregate_data(read=False):
"""
This function processes raw_data and aggregates all the segments labels. Places all the files in the agg_data folder.
Args:
read: boolean, if set to true it will read the data from agg_data folder as long as all the files are found
inside the
folder.
Returns:
Nothing.
"""
"""
Helper functions
"""
def aggregate_files(input_path, output_path, labels_dict):
files = [f for f in listdir(input_path) if isfile(join(input_path, f))]
files = [file for file in files if ".keep" not in file]
# files.remove(".keep")
all_results = pd.DataFrame({'label': [], 'segment': []})
for f in files:
data = pd.read_csv(join(input_path, f), names=["idx", "segment", "label"])
data['label'] = data['label'].apply(lambda x: label_to_vector(x, labels_dict, 12))
labels_data = data[['idx', 'label']]
labels = labels_data.groupby("idx").sum()
segments = data[['idx', 'segment']].set_index('idx').drop_duplicates()
result = pd.merge(labels, segments, left_index=True, right_index=True)
all_results = pd.concat([all_results, result])
all_results.reset_index(drop=True, inplace=True)
folder_output_path = "agg_data"
with open(join(output_path, "agg_data.pkl"), "wb") as output_file:
pickle.dump(all_results, output_file)
"""
main code of aggregate_data
"""
input_path = "raw_data"
output_path = "agg_data"
with open("labels.pkl", "rb") as labels_file:
labels_dict = pickle.load(labels_file)
file_exists = isfile(join(output_path, "agg_data.pkl"))
if file_exists and read:
print("agg_data.pkl are already in agg_data/")
else:
print("Processing dataset in one file ...")
aggregate_files(input_path, output_path, labels_dict)
def aggregate_data_attribute_level(attribute, mode, num_labels, read = False):
def aggregate_lines(input_file, output_file, labels_dict):
data = pd.read_csv(input_file, names=["idx", "segment", "label"])
data['label'] = data['label'].apply(lambda x: label_to_vector(x, labels_dict, num_labels))
labels_data = data[['idx', 'label']]
labels = labels_data.groupby("idx").sum()
segments = data[['idx', 'segment']].set_index('idx').drop_duplicates()
result = pd.merge(labels, segments, left_index=True, right_index=True)
# result.reset_index(drop=True, inplace=True)
# all_results = pd.concat([all_results, result])
# all_results.reset_index(drop=True, inplace=True)
with open(output_file, "wb") as output_file:
pickle.dump(result, output_file)
label_file = "labels_" + attribute + ".pkl"
with open(label_file, "rb") as labels_file:
labels_dict = pickle.load(labels_file)
output_file = join("agg_data", attribute + '_' + mode + '.pkl')
input_file = join('attribute_dataset', attribute + '_' + mode + '.csv')
file_exists = isfile(output_file)
if file_exists and read:
print("data already aggregated, reading ...")
else:
print("Processing csv file ...")
aggregate_lines(input_file, output_file, labels_dict)
def get_absent_words(dictionary, word2vector):
"""
This function check if the words inside dictionary are present in word2vector which is a dictionary coming from a word
embedding.
Args:
dictionary: set, set containing strings of words
word2vector: dictionary, the keys are the words and the values are the embeddings
Returns:
absent_words: list, list containing all the words that weren't found in the word embeddings word2vector
"""
absent_words = []
for word in dictionary:
try:
word2vector[word]
except KeyError:
absent_words.append(word)
return absent_words
def attr_value_labels(attribute):
if attribute == 'Retention Period':
labels = OrderedDict([('Stated Period', 0),
('Limited', 1),
('Indefinitely', 2),
('Unspecified', 3)])
elif attribute == 'Retention Purpose':
labels = OrderedDict([('Advertising', 0),
('Analytics/Research', 1),
('Legal requirement', 2),
('Marketing', 3),
('Perform service', 4),
('Service operation and security', 5),
('Unspecified', 6)])
elif attribute == 'Notification Type':
labels = OrderedDict([('General notice in privacy policy', 0),
('General notice on website', 1),
('No notification', 2),
('Personal notice', 3),
('Unspecified', 4)])
elif attribute == 'Security Measure':
labels = OrderedDict([('Generic', 0),
('Data access limitation', 1),
('Privacy review/audit', 2),
('Privacy training', 3),
('Privacy/Security program', 4),
('Secure data storage', 5),
('Secure data transfer', 6),
('Secure user authentication', 7),
('Unspecified', 8)])
elif attribute == 'Audience Type':
labels = OrderedDict([('Children', 0),
('Californians', 1),
('Citizens from other countries', 2),
('Europeans', 3)])
elif attribute == 'User Type':
labels = OrderedDict([('User with account', 0),
('User without account', 1),
('Unspecified', 2)])
elif attribute == 'Access Scope':
labels = OrderedDict([('Profile data', 0),
('Transactional data', 1),
('User account data', 2),
('Other data about user', 3),
('Unspecified', 4)])
elif attribute == 'Does or Does Not':
labels = OrderedDict([('Does', 0),
('Does Not', 1)])
elif attribute == 'Access Type':
labels = OrderedDict([('Deactivate account', 0),
('Delete account (full)', 1),
('Delete account (partial)', 2),
('Edit information', 3),
('View', 4),
('None', 5),
('Unspecified', 6)])
elif attribute == 'Action First-Party':
labels = OrderedDict([('Collect from user on other websites', 0),
('Collect in mobile app', 1),
('Collect on mobile website', 2),
('Collect on website', 3),
('Receive from other parts of company/affiliates', 4),
('Receive from other service/third-party (named)', 5),
('Receive from other service/third-party (unnamed)', 6),
('Track user on other websites', 7),
('Unspecified', 8)])
elif attribute == 'Action Third-Party':
labels = OrderedDict([('Collect on first party website/app', 0),
('Receive/Shared with', 1),
('See', 2),
('Track on first party website/app', 3),
('Unspecified', 4)])
elif attribute == 'Third Party Entity':
labels = OrderedDict([('Named third party', 0),
('Other part of company/affiliate', 1),
('Other users', 2),
('Public', 3),
('Unnamed third party', 4),
('Unspecified', 5)])
elif attribute == 'Choice Scope':
labels = OrderedDict([('Collection', 0),
('First party collection', 1),
('First party use', 2),
('Third party sharing/collection', 3),
('Third party use', 4),
('Both', 5),
('Use', 6),
('Unspecified', 7)])
elif attribute == 'Choice Type':