File size: 6,425 Bytes
afcb4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import tarfile
import zipfile
import gzip
import requests
from random import shuffle, seed

from glob import glob
from itertools import chain
import gdown

validation_ratio = 0.2
top_n = 10


def wget(url, cache_dir: str = './cache', gdrive_filename: str = None):
    """ wget and uncompress data_iterator """
    os.makedirs(cache_dir, exist_ok=True)
    if url.startswith('https://drive.google.com'):
        assert gdrive_filename is not None, 'please provide fileaname for gdrive download'
        gdown.download(url, f'{cache_dir}/{gdrive_filename}', quiet=False)
        filename = gdrive_filename
    else:
        filename = os.path.basename(url)
    with open(f'{cache_dir}/{filename}', "wb") as f:
        r = requests.get(url)
        f.write(r.content)
    path = f'{cache_dir}/{filename}'

    if path.endswith('.tar.gz') or path.endswith('.tgz') or path.endswith('.tar'):
        if path.endswith('.tar'):
            tar = tarfile.open(path)
        else:
            tar = tarfile.open(path, "r:gz")
        tar.extractall(cache_dir)
        tar.close()
        os.remove(path)
    elif path.endswith('.zip'):
        with zipfile.ZipFile(path, 'r') as zip_ref:
            zip_ref.extractall(cache_dir)
        os.remove(path)
    elif path.endswith('.gz'):
        with gzip.open(path, 'rb') as f:
            with open(path.replace('.gz', ''), 'wb') as f_write:
                f_write.write(f.read())
        os.remove(path)


def get_training_data():
    """ Get RelBERT training data

    Returns
    -------
    pairs: dictionary of list (positive pairs, negative pairs)
    {'1b': [[0.6, ('office', 'desk'), ..], [[-0.1, ('aaa', 'bbb'), ...]]
    """
    cache_dir = 'cache'
    os.makedirs(cache_dir, exist_ok=True)
    remove_relation = None
    path_answer = f'{cache_dir}/Phase2Answers'
    path_scale = f'{cache_dir}/Phase2AnswersScaled'
    url = 'https://drive.google.com/u/0/uc?id=0BzcZKTSeYL8VYWtHVmxUR3FyUmc&export=download'
    filename = 'SemEval-2012-Platinum-Ratings.tar.gz'
    if not (os.path.exists(path_scale) and os.path.exists(path_answer)):
        wget(url, gdrive_filename=filename, cache_dir=cache_dir)
    files_answer = [os.path.basename(i) for i in glob(f'{path_answer}/*.txt')]
    files_scale = [os.path.basename(i) for i in glob(f'{path_scale}/*.txt')]
    assert files_answer == files_scale, f'files are not matched: {files_scale} vs {files_answer}'
    positives = {}
    negatives = {}
    all_relation_type = {}
    positives_score = {}
    seed(42)
    # score_range = [90.0, 88.7]  # the absolute value of max/min prototypicality rating
    for i in files_scale:
        relation_id = i.split('-')[-1].replace('.txt', '')
        if remove_relation and int(relation_id[:-1]) in remove_relation:
            continue
        with open(f'{path_answer}/{i}', 'r') as f:
            lines_answer = [_l.replace('"', '').split('\t') for _l in f.read().split('\n')
                            if not _l.startswith('#') and len(_l)]
            relation_type = list(set(list(zip(*lines_answer))[-1]))
            assert len(relation_type) == 1, relation_type
            relation_type = relation_type[0]
        with open(f'{path_scale}/{i}', 'r') as f:
            # list of tuple [score, ("a", "b")]
            scales = [[float(_l[:5]), _l[6:].replace('"', '')] for _l in f.read().split('\n')
                      if not _l.startswith('#') and len(_l)]
            scales = sorted(scales, key=lambda _x: _x[0])
            # positive pairs are in the reverse order of prototypicality score
            positive_pairs = [[s, tuple(p.split(':'))] for s, p in filter(lambda _x: _x[0] > 0, scales)]
            positive_pairs = sorted(positive_pairs, key=lambda x:  x[0], reverse=True)

            positive_pairs = positive_pairs[:min(top_n, len(positive_pairs))]
            shuffle(positive_pairs)
            positives_score[relation_id] = positive_pairs
            positives[relation_id] = list(list(zip(*positive_pairs))[1])

            negative_pairs = [tuple(p.split(':')) for s, p in filter(lambda _x: _x[0] < 0, scales)]
            shuffle(negative_pairs)
            negatives[relation_id] = negative_pairs

        all_relation_type[relation_id] = relation_type

    # consider positive from other relation as negative
    for k in positives.keys():
        negatives[k] += list(chain(*[_v for _k, _v in positives.items() if _k != k]))

    # split train & validation

    positives_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in positives.items()}
    positives_train = {k: v[int(len(v) * validation_ratio):] for k, v in positives.items()}

    negatives_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in negatives.items()}
    negatives_train = {k: v[int(len(v) * validation_ratio):] for k, v in negatives.items()}

    positives_score_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in positives_score.items()}
    positives_score_train = {k: v[int(len(v) * validation_ratio):] for k, v in positives_score.items()}

    outputs = []
    for positives, negatives, positives_score in zip(
            [positives_train, positives_valid],
            [negatives_train, negatives_valid],
            [positives_score_train, positives_score_valid]):
        pairs = {k: [positives[k], negatives[k]] for k in positives.keys()}
        parent = list(set([i[:-1] for i in all_relation_type.keys()]))
        relation_structure = {p: [i for i in all_relation_type.keys() if p == i[:-1]] for p in parent}
        for k, v in relation_structure.items():
            positive = list(chain(*[positives_score[_v] for _v in v]))
            positive = list(list(zip(*sorted(positive, key=lambda x: x[0], reverse=True)))[1])
            negative = []
            for _k, _v in relation_structure.items():
                if _k != k:
                    negative += list(chain(*[positives[__v] for __v in _v]))
            pairs[k] = [positive, negative]
        outputs.append([{'relation_type': k, 'positives': pos, 'negatives': neg} for k, (pos, neg) in pairs.items()])
    return outputs


if __name__ == '__main__':
    data_train, data_valid = get_training_data()
    with open('dataset/train.jsonl', 'w') as f_writer:
        f_writer.write('\n'.join([json.dumps(i) for i in data_train]))
    with open('dataset/valid.jsonl', 'w') as f_writer:
        f_writer.write('\n'.join([json.dumps(i) for i in data_valid]))