forked from ShannonAI/mrc-for-flat-nested-ner
-
Notifications
You must be signed in to change notification settings - Fork 1
/
illegal_entity_boundary.py
209 lines (179 loc) · 11.6 KB
/
illegal_entity_boundary.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: illegal_entity_boundary.py
from transformers import AutoTokenizer
def load_dataexamples(file_path, ):
with open(file_path, "r") as f:
datalines = f.readlines()
sentence_collections = []
sentence_label_collections = []
word_collections = []
word_label_collections = []
for data_item in datalines:
data_item = data_item.strip()
if len(data_item) != 0:
word, label = tuple(data_item.split(" "))
word_collections.append(word)
word_label_collections.append(label)
else:
sentence_collections.append(word_collections)
sentence_label_collections.append(word_label_collections)
word_collections = []
word_label_collections = []
return sentence_collections, sentence_label_collections
def find_data_instance(file_path, search_string):
sentence_collections, sentence_label_collections = load_dataexamples(file_path)
for sentence_lst, label_lst in zip(sentence_collections, sentence_label_collections):
sentence_str = "".join(sentence_lst)
if search_string in sentence_str:
print(sentence_str)
print("-"*10)
print(sentence_lst)
print(label_lst)
print("=*"*10)
def find_illegal_entity(query, context_tokens, labels, model_path, is_chinese=True, do_lower_case=True):
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, do_lower_case=do_lower_case)
if is_chinese:
context = "".join(context_tokens)
else:
context = " ".join(context_tokens)
start_positions = []
end_positions = []
origin_tokens = context_tokens
print("check labels in ")
print(len(origin_tokens))
print(len(labels))
for label_idx, label_item in enumerate(labels):
if "B-" in label_item:
start_positions.append(label_idx)
if "S-" in label_item:
end_positions.append(label_idx)
start_positions.append(label_idx)
if "E-" in label_item:
end_positions.append(label_idx)
print("origin entity tokens")
for start_item, end_item in zip(start_positions, end_positions):
print(origin_tokens[start_item: end_item + 1])
query_context_tokens = tokenizer.encode_plus(query, context,
add_special_tokens=True,
max_length=500000,
return_overflowing_tokens=True,
return_token_type_ids=True)
if tokenizer.pad_token_id in query_context_tokens["input_ids"]:
non_padded_ids = query_context_tokens["input_ids"][
: query_context_tokens["input_ids"].index(tokenizer.pad_token_id)]
else:
non_padded_ids = query_context_tokens["input_ids"]
non_pad_tokens = tokenizer.convert_ids_to_tokens(non_padded_ids)
first_sep_token = non_pad_tokens.index("[SEP]")
end_sep_token = len(non_pad_tokens) - 1
new_start_positions = []
new_end_positions = []
if len(start_positions) != 0:
for start_index, end_index in zip(start_positions, end_positions):
if is_chinese:
answer_text_span = " ".join(context[start_index: end_index + 1])
else:
answer_text_span = " ".join(context.split(" ")[start_index: end_index + 1])
new_start, new_end = _improve_answer_span(query_context_tokens["input_ids"], first_sep_token, end_sep_token,
tokenizer, answer_text_span)
new_start_positions.append(new_start)
new_end_positions.append(new_end)
else:
new_start_positions = start_positions
new_end_positions = end_positions
# clip out-of-boundary entity positions.
new_start_positions = [start_pos for start_pos in new_start_positions if start_pos < 500000]
new_end_positions = [end_pos for end_pos in new_end_positions if end_pos < 500000]
print("print tokens :")
for start_item, end_item in zip(new_start_positions, new_end_positions):
print(tokenizer.convert_ids_to_tokens(query_context_tokens["input_ids"][start_item: end_item + 1]))
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text, return_subtoken_start=False):
"""Returns tokenized answer spans that better match the annotated answer."""
doc_tokens = [str(tmp) for tmp in doc_tokens]
answer_tokens = tokenizer.encode(orig_answer_text, add_special_tokens=False)
tok_answer_text = " ".join([str(tmp) for tmp in answer_tokens])
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start : (new_end+1)])
if text_span == tok_answer_text:
if not return_subtoken_start:
return (new_start, new_end)
tokens = tokenizer.convert_ids_to_tokens(doc_tokens[new_start: (new_end + 1)])
if "##" not in tokens[-1]:
return (new_start, new_end)
else:
for idx in range(len(tokens)-1, -1, -1):
if "##" not in tokens[idx]:
new_end = new_end - (len(tokens)-1 - idx)
return (new_start, new_end)
return (input_start, input_end)
if __name__ == "__main__":
# file_path = "/data/xiaoya/datasets/ner/msra/train.char.bmes"
# search_string = "美亚股份"
# find_data_instance(file_path, search_string)
#
# print("=%"*20)
# print("check entity boundary")
# print("=&"*20)
print(">>> check for Chinese data example ... ...")
context_tokens = ['1', '美', '亚', '股', '份', '3', '2', '.', '6', '6', '2', '民', '族', '集', '团', '2', '2', '.', '3',
'8', '3', '鲁', '石', '化', 'A', '1', '9', '.', '1', '1', '4', '四', '川', '湖', '山', '1', '7', '.',
'0', '9', '5', '太', '原', '刚', '玉', '1', '0', '.', '5', '8', '1', '咸', '阳', '偏', '转', '1', '6',
'.', '1', '1', '2', '深', '华', '发', 'A', '1', '5', '.', '6', '6', '3', '渝', '开', '发', 'A', '1',
'5', '.', '5', '2', '4', '深', '发', '展', 'A', '1', '3', '.', '8', '9', '5', '深', '纺', '织', 'A',
'1', '3', '.', '2', '2', '1', '太', '极', '实', '业', '2', '3', '.', '2', '2', '2', '友', '好', '集',
'团', '2', '2', '.', '1', '4', '3', '双', '虎', '涂', '料', '2', '0', '.', '2', '0', '4', '新', '潮',
'实', '业', '1', '5', '.', '5', '8', '5', '信', '联', '股', '份', '1', '2', '.', '5', '7', '1', '氯',
'碱', '化', '工', '2', '1', '.', '1', '7', '2', '百', '隆', '股', '份', '1', '5', '.', '6', '4', '3',
'贵', '华', '旅', '业', '1', '5', '.', '1', '5', '4', '南', '洋', '实', '业', '1', '4', '.', '5', '0',
'5', '福', '建', '福', '联', '1', '3', '.', '8', '0']
labels = ['O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O',
'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT',
'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O',
'O', 'B-NT', 'M-NT',
'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O',
'O',
'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O',
'O', 'O', 'O',
'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O',
'O', 'O', 'O',
'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT',
'O', 'O',
'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT',
'E-NT',
'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT',
'M-NT', 'M-NT',
'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O',
'B-NT',
'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O', 'O', 'O', 'B-NT', 'M-NT', 'M-NT', 'E-NT', 'O', 'O', 'O', 'O',
'O']
query = "组织机构"
model_path = "/data/nfsdata/nlp/BERT_BASE_DIR/chinese_L-12_H-768_A-12"
find_illegal_entity(query, context_tokens, labels, model_path, is_chinese=True, do_lower_case=True)
print("$$$$$"*20)
print(">>> check for English data example ... ...")
query = "organization"
context_tokens = ['RUGBY', 'LEAGUE', '-', 'EUROPEAN', 'SUPER', 'LEAGUE', 'RESULTS', '/', 'STANDINGS', '.', 'LONDON',
'1996-08-24', 'Results', 'of', 'European', 'Super', 'League', 'rugby', 'league', 'matches', 'on',
'Saturday', ':', 'Paris', '14', 'Bradford', '27', 'Wigan', '78', 'Workington', '4', 'Standings',
'(', 'tabulated', 'under', 'played', ',', 'won', ',', 'drawn', ',', 'lost', ',', 'points', 'for',
',', 'against', ',', 'total', 'points', ')', ':', 'Wigan', '22', '19', '1', '2', '902', '326',
'39', 'St', 'Helens', '21', '19', '0', '2', '884', '441', '38', 'Bradford', '22', '17', '0', '5',
'767', '409', '34', 'Warrington', '21', '12', '0', '9', '555', '499', '24', 'London', '21', '11',
'1', '9', '555', '462', '23', 'Sheffield', '21', '10', '0', '11', '574', '696', '20', 'Halifax',
'21', '9', '1', '11', '603', '552', '19', 'Castleford', '21', '9', '0', '12', '548', '543', '18',
'Oldham', '21', '8', '1', '12', '439', '656', '17', 'Leeds', '21', '6', '0', '15', '531', '681',
'12', 'Paris', '22', '3', '1', '18', '398', '795', '7', 'Workington', '22', '2', '1', '19', '325',
'1021', '5']
labels = ['B-MISC', 'E-MISC', 'O', 'B-MISC', 'I-MISC', 'E-MISC', 'O', 'O', 'O', 'O', 'S-LOC', 'O', 'O', 'O',
'B-MISC', 'I-MISC', 'E-MISC', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'S-ORG', 'O', 'S-ORG', 'O',
'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-ORG', 'E-ORG', 'O', 'O', 'O', 'O', 'O', 'O',
'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O',
'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O',
'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'S-ORG', 'O', 'O',
'O', 'O', 'O', 'O', 'O']
model_path = "/data/xiaoya/models/bert_cased_large"
find_illegal_entity(query, context_tokens, labels, model_path, is_chinese=False, do_lower_case=False)