File size: 4,523 Bytes
7f7285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-

'''
@Author     : Jiangjie Chen
@Time       : 2020/7/20 17:34
@Contact    : [email protected]
@Description: 
'''

import tensorflow as tf
import cjjpy as cjj
import os
import re
import ujson as json
from collections import defaultdict

pj_prefix = cjj.AbsParentDir(__file__, '..')


class FEVERLoader:
    def __init__(self, role):
        role = 'dev' if role == 'val' else role
        assert role in ['train', 'dev', 'test', 'eval']
        self.role = role
        self.fever_data = defaultdict(dict)
        self.SUPPORTS = 'SUPPORTS'
        self.REFUTES = 'REFUTES'
        self.NEI = 'NOT ENOUGH INFO'

    def __iter__(self):
        for k in self.fever_data:
            yield k

    def __len__(self):
        return len(self.fever_data)

    def __getitem__(self, item):
        return self.fever_data[item]

    def load_fever(self, retrieve_type='bert', clean_load=True):
        self._load_fever_golden()
        self._load_fever_all()
        self._load_fever_retrieved(retrieve_type, clean_load)

    def _load_json(self, fname):
        with tf.io.gfile.GFile(fname) as f:
            return [json.loads(x) for x in f.readlines()]

    def _new_role(self):
        role = self.role if self.role != 'eval' else 'dev'
        return role

    def _load_fever_golden(self):
        if self.role == 'test':
            postfix = f'data/fever/shared_task_test.jsonl'
            for js in self._load_json(f'{pj_prefix}/{postfix}'):
                self.fever_data[js['id']].update({
                    'id': js['id'],
                    'claim': js['claim']
                })
        else:
            role = self._new_role()
            postfix = f'data/fever/baked_data/golden_{role}.json'
            for js in self._load_json(f'{pj_prefix}/{postfix}'):
                self.fever_data[js['id']].update({
                    'id': js['id'],
                    'claim': js['claim'],
                    'label': js['label'],
                    'golden_evidence': self._clean_evidence(js['evidence'])
                })
        print('* FEVER golden loaded.')

    def _load_fever_all(self):
        role = self._new_role()
        postfix = f'data/fever/baked_data/all_{role}.json'
        for js in self._load_json(f'{pj_prefix}/{postfix}'):
            self.fever_data[js['id']].update({
                'all_evidence': self._clean_evidence(js['evidence'])
            })
        print('* FEVER all loaded.')

    def _load_fever_retrieved(self, retrieve_type, clean_load):
        assert retrieve_type in ['bert']
        postfix = f'data/fever/baked_data/{retrieve_type}_{self.role}.json'
        for js in self._load_json(f'{pj_prefix}/{postfix}'):
            self.fever_data[js['id']].update({
                f'{retrieve_type}_evidence': self._clean_evidence(js['evidence']) if clean_load else js['evidence']
            })
        print(f'* FEVER {retrieve_type} loaded.')

    def clean_text(self, sentence):
        sentence = re.sub(" \-LSB\-.*?\-RSB\-", "", sentence)
        sentence = re.sub("\-LRB\- \-RRB\- ", "", sentence)
        sentence = re.sub(" -LRB-", " ( ", sentence)
        sentence = re.sub("-RRB-", " )", sentence)

        sentence = re.sub(" LSB.*?RSB", "", sentence)
        sentence = re.sub("LRB RRB ", "", sentence)
        sentence = re.sub("LRB", " ( ", sentence)
        sentence = re.sub("RRB", " )", sentence)
        sentence = re.sub("--", "-", sentence)
        sentence = re.sub("``", '"', sentence)
        sentence = re.sub("''", '"', sentence)
        sentence = re.sub('  ', ' ', sentence)
        return sentence

    def clean_title(self, title):
        title = re.sub("_", " ", title)
        title = re.sub(" -LRB-", " ( ", title)
        title = re.sub("-RRB-", " )", title)
        title = re.sub("-COLON-", ":", title)
        title = re.sub('  ', ' ', title)
        return title

    def _clean_evidence(self, evidence):
        cev = []
        for ev in evidence:
            if len(ev) == 4:
                cev.append([self.clean_title(ev[0]), ev[1], self.clean_text(ev[2]), ev[3]])
            elif len(ev) == 3:
                cev.append([self.clean_title(ev[0]), ev[1], self.clean_text(ev[2])])
            elif len(ev) == 0:
                cev.append(ev)
            else:
                raise ValueError(ev)
        return cev


if __name__ == '__main__':
    floader = FEVERLoader('test')
    floader.load_fever('bert', clean_load=False)
    for k in floader:
        print(floader[k])
        input()