forked from PaddlePaddle/PaddleNLP
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtermtree.py
More file actions
Latest commit
416 lines (360 loc) Β· 14 KB
/
Copy pathtermtree.py
File metadata and controls
416 lines (360 loc) Β· 14 KB
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
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
importcsv
importjson
importos
importwarnings
fromtypingimportAny, Dict, List, Optional, Tuple, Union
classTermTreeNode(object):
"""Defination of term node. All members are protected, to keep rigorism of data struct.
Args:
sid (str): term id of node.
term (str): term, common name of this term.
base (str): `cb` indicates concept base, `eb` indicates entity base.
term_type (Optional[str], optional): type of this term, constructs hirechical of `term` node. Defaults to None.
hyper (Optional[str], optional): parent type of a `type` node. Defaults to None.
node_type (str, optional): type statement of node, `type` or `term`. Defaults to "term".
alias (Optional[List[str]], optional): alias of this term. Defaults to None.
alias_ext (Optional[List[str]], optional): extended alias of this term, CANNOT be used in matching.
Defaults to None.
sub_type (Optional[List[str]], optional): grouped by some term. Defaults to None.
sub_term (Optional[List[str]], optional): some lower term. Defaults to None.
data (Optional[Dict[str, Any]], optional): to sore full imformation of a term. Defaults to None.
"""
def__init__(
self,
sid: str,
term: str,
base: str,
node_type: str="term",
term_type: Optional[str] =None,
hyper: Optional[str] =None,
level: Optional[int] =None,
alias: Optional[List[str]] =None,
alias_ext: Optional[List[str]] =None,
sub_type: Optional[List[str]] =None,
sub_term: Optional[List[str]] =None,
data: Optional[Dict[str, Any]] =None,
):
self._sid=sid
self._term=term
self._base=base
self._term_type=term_type
self._hyper=hyper
self._sub_term=sub_termifsub_termisnotNoneelse []
self._sub_type=sub_typeifsub_typeisnotNoneelse []
self._alias=aliasifaliasisnotNoneelse []
self._alias_ext=alias_extifalias_extisnotNoneelse []
self._data=data
self._level=level
self._node_type=node_type
self._sons=set()
def__str__(self):
ifself._dataisnotNone:
returnjson.dumps(self._data, ensure_ascii=False)
else:
res= {
"termid": self._sid,
"term": self._term,
"src": self._base,
"alias": self._alias,
"alias_ext": self._alias_ext,
"termtype": self._term_type,
"subterms": self._sub_term,
"subtype": self._sub_type,
"links": [],
}
returnjson.dumps(res, ensure_ascii=False)
@property
defsid(self):
returnself._sid
@property
defterm(self):
returnself._term
@property
defbase(self):
returnself._base
@property
defalias(self):
returnself._alias
@property
defalias_ext(self):
returnself._alias_ext
@property
deftermtype(self):
returnself._term_type
@property
defsubtype(self):
returnself._sub_type
@property
defsubterm(self):
returnself._sub_term
@property
defhyper(self):
returnself._hyper
@property
deflevel(self):
returnself._level
@property
defsons(self):
returnself._sons
@property
defnode_type(self):
returnself._node_type
defadd_son(self, son_name):
self._sons.add(son_name)
@classmethod
deffrom_dict(cls, data: Dict[str, Any]):
"""Build a node from dictionary data.
Args:
data (Dict[str, Any]): Dictionary data contain all k-v data.
Returns:
[type]: TermTree node object.
"""
returncls(
sid=data["termid"],
term=data["term"],
base=data["src"],
term_type=data["termtype"],
sub_type=data["subtype"],
sub_term=data["subterms"],
alias=data["alias"],
alias_ext=data["alias_ext"],
data=data,
)
@classmethod
deffrom_json(cls, json_str: str):
"""Build a node from JSON string.
Args:
json_str (str): JSON string formatted by TermTree data.
Returns:
[type]: TermTree node object.
"""
dict_data=json.loads(json_str)
returncls.from_dict(dict_data)
classTermTree(object):
"""TermTree class."""
def__init__(self):
self._nodes: Dict[str, TermTreeNode] = {}
self._root=TermTreeNode(sid="root", term="root", base="cb", node_type="root", level=0)
self._nodes["root"] =self.root
self._index= {}
def__build_sons(self):
fornodeinself._nodes:
self.__build_son(self._nodes[node])
def__getitem__(self, item):
returnself._nodes[item]
def__contains__(self, item):
returniteminself._nodes
def__iter__(self):
returnself._nodes.__iter__()
@property
defroot(self):
returnself._root
def__load_type(self, file_path: str):
withopen(file_path, "rt", newline="", encoding="utf8") ascsvfile:
file_handler=csv.DictReader(csvfile, delimiter="\t")
forrowinfile_handler:
ifrow["type-1"] notinself:
self.add_type(type_name=row["type-1"], hyper_type="root")
ifrow["type-2"] !=""androw["type-2"] notinself:
self.add_type(type_name=row["type-2"], hyper_type=row["type-1"])
ifrow["type-3"] !=""androw["type-3"] notinself:
self.add_type(type_name=row["type-3"], hyper_type=row["type-2"])
def__judge_term_node(self, node: TermTreeNode) ->bool:
ifnode.termtypenotinself:
raiseValueError(f"Term type of new node {node.termtype} does not exists.")
ifnode.sidinself:
warnings.warn(f"{node.sid} exists, will be replaced by new node.")
defadd_term(
self,
term: Optional[str] =None,
base: Optional[str] =None,
term_type: Optional[str] =None,
sub_type: Optional[List[str]] =None,
sub_term: Optional[List[str]] =None,
alias: Optional[List[str]] =None,
alias_ext: Optional[List[str]] =None,
data: Optional[Dict[str, Any]] =None,
):
"""Add a term into TermTree.
Args:
term (str): common name of name.
base (str): term is concept or entity.
term_type (str): term type of this term
sub_type (Optional[List[str]], optional): sub type of this term, must exists in TermTree. Defaults to None.
sub_terms (Optional[List[str]], optional): sub terms of this term. Defaults to None.
alias (Optional[List[str]], optional): alias of this term. Defaults to None.
alias_ext (Optional[List[str]], optional): . Defaults to None.
data (Optional[Dict[str, Any]], optional): [description]. Defaults to None.
"""
ifdataisnotNone:
new_node=TermTreeNode.from_dict(data)
else:
new_node=TermTreeNode(
sid=f"{term_type}_{base}_{term}",
term=term,
base=base,
term_type=term_type,
sub_term=sub_term,
sub_type=sub_type,
alias=alias,
alias_ext=alias_ext,
node_type="term",
)
self.__judge_term_node(new_node)
self._nodes[new_node.sid] =new_node
self.__build_index(new_node)
defadd_type(self, type_name, hyper_type):
iftype_nameinself._nodes:
raiseValueError(f"Term Type {type_name} exists.")
ifhyper_typenotinself._nodes:
raiseValueError(f"Hyper type {hyper_type} does not exist, please add it first.")
ifself._nodes[hyper_type].level==3:
raiseValueError(
"Term type schema must be 3-LEVEL, 3rd level type node should not be a parent of type node."
)
self._nodes[type_name] =TermTreeNode(
sid=type_name,
term=type_name,
base=None,
hyper=hyper_type,
node_type="type",
level=self._nodes[hyper_type].level+1,
)
self.__build_index(self._nodes[type_name])
def__load_file(self, file_path: str):
withopen(file_path, encoding="utf-8") asfp:
forlineinfp:
data=json.loads(line)
self.add_term(data=data)
def__build_son(self, node: TermTreeNode):
"""Build sons of a node
Args:
node (TermTreeNode): son node.
"""
type_node=None
ifnode.termtypeisnotNone:
type_node=self._nodes[node.termtype]
elifnode.hyperisnotNone:
type_node=self._nodes[node.hyper]
iftype_nodeisnotNone:
type_node.add_son(node.sid)
forsub_typeinnode.subtype:
sub_type_node=self._nodes[sub_type]
sub_type_node.add_son(node.sid)
defbuild_son(self, node: str):
self.__build_son(self[node])
def__build_index(self, node: TermTreeNode):
ifnode.termnotinself._index:
self._index[node.term] = []
self._index[node.term].append(node.sid)
foraliainnode.alias:
ifalianotinself._index:
self._index[alia] = []
self._index[alia].append(node.sid)
def__judge_hyper(self, source_id, target_id) ->bool:
queue= [source_id]
visited_node= {source_id}
whilelen(queue) >0:
cur_id=queue.pop(0)
ifcur_id==target_id:
returnTrue
cur_node=self._nodes[cur_id]
edge= []
ifcur_node.hyperisnotNone:
edge.append(cur_node.hyper)
ifcur_node.termtypeisnotNone:
edge.append(cur_node.termtype)
edge.extend(cur_node.subtype)
fornext_idinedge:
ifnext_idnotinvisited_node:
queue.append(next_id)
visited_node.add(next_id)
returnFalse
deffind_term(self, term: str, term_type: Optional[str] =None) ->Tuple[bool, Union[List[str], None]]:
"""Find a term in Term Tree. If term not exists, return None.
If `term_type` is not None, will find term with this type.
Args:
term (str): term to look up.
term_type (Optional[str], optional): find term in this term_type. Defaults to None.
Returns:
Union[None, List[str]]: [description]
"""
iftermnotinself._index:
returnFalse, None
else:
ifterm_typeisNone:
returnTrue, self._index[term]
else:
out= []
forterm_idinself._index[term]:
ifself.__judge_hyper(term_id, term_type) isTrue:
out.append(term_id)
iflen(out) >0:
returnTrue, out
else:
returnFalse, None
defbuild_from_dir(self, term_schema_path, term_data_path, linking=True):
"""Build TermTree from a directory which should contain type schema and term data.
Args:
dir ([type]): [description]
"""
self.__load_type(term_schema_path)
iflinking:
self.__load_file(term_data_path)
self.__build_sons()
@classmethod
deffrom_dir(cls, term_schema_path, term_data_path, linking=True) ->"TermTree":
"""Build TermTree from a directory which should contain type schema and term data.
Args:
source_dir ([type]): [description]
Returns:
TermTree: [description]
"""
term_tree=cls()
term_tree.build_from_dir(term_schema_path, term_data_path, linking)
returnterm_tree
def__dfs(self, cur_id: str, depth: int, path: Dict[str, str], writer: csv.DictWriter):
cur_node=self._nodes[cur_id]
ifcur_node.node_type=="term":
return
ifdepth>0:
path[f"type-{depth}"] =cur_id
ifpath["type-1"] !="":
writer.writerow(path)
forsonincur_node.sons:
self.__dfs(son, depth+1, path, writer)
ifdepth>0:
path[f"type-{depth}"] =""
defsave(self, save_dir):
"""Save term tree to directory `save_dir`
Args:
save_dir ([type]): Directory.
"""
ifos.path.exists(save_dir) isFalse:
os.makedirs(save_dir, exist_ok=True)
out_path= {}
foriinrange(1, 3):
out_path[f"type-{i}"] =""
withopen(f"{save_dir}/termtree_type.csv", "wt", encoding="utf-8", newline="") asfp:
fieldnames= ["type-1", "type-2", "type-3"]
csv_writer=csv.DictWriter(fp, delimiter="\t", fieldnames=fieldnames)
csv_writer.writeheader()
self.__dfs("root", 0, out_path, csv_writer)
withopen(f"{save_dir}/termtree_data", "w", encoding="utf-8", newline="") asfp:
fornidinself:
node=self[nid]
ifnode.node_type=="term":
print(node, file=fp)