File size: 12,920 Bytes
bcb1848 |
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 |
"""
NER λͺ¨λΈμ μ΄μ©νμ¬ μμ
νλ μ½λμ
λλ€.
"""
import re
import torch
import numpy as np
from collections import Counter
device = "cuda:0" if torch.cuda.is_available() else "cpu"
def ner_tokenizer(text, max_seq_length, checkpoint):
"""
NERμ μν΄ ν
μ€νΈλ₯Ό ν ν°νν©λλ€.
Args:
sent: μ²λ¦¬νκ³ μ νλ ν
μ€νΈλ₯Ό μ
λ ₯λ°μ΅λλ€.
max_seq_length: BERTμ configμμ μ²λ¦¬ κ°λ₯ν μ΅λ λ¬Έμμ΄ κΈΈμ΄λ 512μ
λλ€. μ΅λ κΈΈμ΄λ₯Ό λμ΄μμ§ μλλ‘, ν
μ€νΈ κΈΈμ΄κ° 512λ₯Ό λμ΄κ° κ²½μ° μ¬λ¬ κ°μ λ¬Έμμ΄λ‘ λΆλ¦¬ν©λλ€.
λ¬Έλ§₯ μ 보λ₯Ό κ³ λ €νλ―λ‘ κ°λ₯ν κΈ΄ κΈΈμ΄λ‘ chunkingνλ κ²μ΄ μ’μ μ±λ₯μ 보μ₯ν μ μμ΅λλ€.
checkpoint: NER λͺ¨λΈμ λν μ 보λ₯Ό λΆλ¬λ€μ
λλ€.
Return:
ner_tokenizer_dict: μλ μΈ μμλ₯Ό ν¬ν¨ν λμ
λ리μ
λλ€.
input_ids: κ° ν ν°μ λͺ¨λΈ λμ
λ리μμμ μμ΄λκ°μ
λλ€.
attention_mask: κ° ν ν°μ μ΄ν μ
λ§μ€ν¬ νμ±ν μ¬λΆμ
λλ€.
token_type_ids: κ°μ²΄λͺ
μΈμ λ ν ν°μ κ²½μ° κ·Έ νμ
μ μμ΄λ(μ«μ μ‘°ν©)λ₯Ό λ°νν©λλ€.
"""
#μ μ₯λ λͺ¨λΈμ ν ν¬λμ΄μ λ₯Ό λΆλ¬μ΅λλ€.
tokenizer = checkpoint['tokenizer']
#κ°κ° ν¨λ©, λ¬Έμ₯ μμ, λ¬Έμ₯ λμ λνλ΄λ νΉλ³ν ν ν°λ€μ ID κ°λ€μ κ°μ Έμ΅λλ€.
pad_token_id = tokenizer.pad_token_id
cls_token_id = tokenizer.cls_token_id
sep_token_id = tokenizer.sep_token_id
#μ΄μ μμ μ μ μ₯νλ λ³μλ₯Ό μ΄κΈ°νν©λλ€.
pre_syllable = "_"
#ν ν¬λμ΄μ§λ κ²°κ³Όλ₯Ό μ μ₯ν 리μ€νΈλ€μ μ΄κΈ°νν©λλ€.
input_ids = [pad_token_id] * (max_seq_length - 1)
attention_mask = [0] * (max_seq_length - 1)
token_type_ids = [0] * max_seq_length
#μ
λ ₯λ ν
μ€νΈλ₯Ό μ΅λ μνμ€ κΈΈμ΄μ λ§κ² μλΌλ
λλ€.
text = text[:max_seq_length-2]
#ν
μ€νΈμ κ° μμ μ λν΄ λ°λ³΅λ¬Έμ μ€νν©λλ€.
for i, syllable in enumerate(text):
if syllable == '_':
pre_syllable = syllable
if pre_syllable != "_":
syllable = '##' + syllable
pre_syllable = syllable
#ν ν°μ λͺ¨λΈμ λ¨μ΄ μ¬μ μ μλ ID κ°μΌλ‘ λ³ννμ¬ input_ids 리μ€νΈμ μ μ₯ν©λλ€.
input_ids[i] = tokenizer.convert_tokens_to_ids(syllable)
#ν΄λΉ μμΉμ ν ν°μ λν μ΄ν
μ
λ§μ€ν¬λ₯Ό νμ±νν©λλ€.
attention_mask[i] = 1
#μ
λ ₯ μνμ€μ μμμλ cls_token_idλ₯Ό, λμλ sep_token_idλ₯Ό μΆκ°ν©λλ€.
input_ids = [cls_token_id] + input_ids[:-1] + [sep_token_id]
#μ΄ν
μ
λ§μ€ν¬λ μμκ³Ό λ ν ν°μ κ³ λ €νμ¬ μμ ν©λλ€.
attention_mask = [1] + attention_mask[:-1] + [1]
ner_tokenizer_dict = {"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids}
return ner_tokenizer_dict
def get_ner_predictions(text, checkpoint):
"""
ν ν°νν λ¬Έμ₯(tokenized_sent)κ³Ό μμΈ‘ν νκ·Έ(pred_tags) κ°μ λ§λλ ν¨μμ
λλ€.
Args:
text: NER μμΈ‘μ νμλ‘ νλ ν
μ€νΈλ₯Ό μ
λ ₯ν©λλ€.
checkpoint: μ μ₯ν λͺ¨λΈμ λΆλ¬λ€μ
λλ€.
Returns:
tokenized_sent: λͺ¨λΈ μ
λ ₯μ μν ν ν°νλ λ¬Έμ₯ μ 보μ
λλ€.
pred_tags: κ° ν ν°μ λν μμΈ‘λ νκ·Έλ€μ ν¬ν¨ν©λλ€.
"""
#μ μ₯ν λͺ¨λΈμ λΆλ¬λ€μ
λλ€.
model = checkpoint['model']
#νκ·Έμ ν΄λΉ νκ·Έμ ID 맀ν μ 보λ₯Ό κ°μ Έμ΅λλ€.
tag2id = checkpoint['tag2id']
model.to(device)
#μ
λ ₯λ ν
μ€νΈμμ 곡백μ μΈλμ€μ½μ΄(_)λ‘ λ체ν©λλ€.
text = text.replace(' ', '_')
#μμΈ‘κ°κ³Ό μ€μ λΌλ²¨μ μ μ₯ν λΉ λ¦¬μ€νΈλ₯Ό μμ±ν©λλ€.
predictions, true_labels = [], []
#ner_tokenizer ν¨μλ₯Ό μ¬μ©νμ¬ ν
μ€νΈλ₯Ό ν ν°νν©λλ€.
tokenized_sent = ner_tokenizer(text, len(text) + 2, checkpoint)
#ν ν°νλ κ²°κ³Όλ₯Ό ν λλ‘ ν
μλ‘ λ³ννμ¬ λͺ¨λΈ μ
λ ₯ νμμ λ§κ² μ€λΉν©λλ€.
input_ids = torch.tensor(
tokenized_sent['input_ids']).unsqueeze(0).to(device)
attention_mask = torch.tensor(
tokenized_sent['attention_mask']).unsqueeze(0).to(device)
token_type_ids = torch.tensor(
tokenized_sent['token_type_ids']).unsqueeze(0).to(device)
#κ·ΈλλμΈνΈ κ³μ°μ μννμ§ μκΈ° μν΄ torch.no_grad() 컨ν
μ€νΈ λ΄μμ λ€μμ μ€νν©λλ€. (eval μμμ΄κΈ° λλ¬Έμ νμ΅μ νμ§ μμ΅λλ€)
with torch.no_grad():
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
#λͺ¨λΈ μΆλ ₯μμ λ‘μ§ κ°μ κ°μ Έμ Numpyκ°μΌλ‘ λ³ννκ³ , λΌλ²¨ IDλ€μ CPU μμ NumPy λ°°μ΄λ‘ κ°μ Έμ΅λλ€.
logits = outputs['logits']
logits = logits.detach().cpu().numpy()
label_ids = token_type_ids.cpu().numpy()
#μμΈ‘λ λΌλ²¨ κ°μ κ°μ Έμμ 리μ€νΈμ μΆκ°ν©λλ€.
predictions.extend([list(p) for p in np.argmax(logits, axis=2)])
#μ€μ λΌλ²¨μ 리μ€νΈμ μΆκ°ν©λλ€.
true_labels.append(label_ids)
#μμΈ‘λ λΌλ²¨ IDλ₯Ό μ€μ νκ·Έλ‘ λ³νν©λλ€.
pred_tags = [list(tag2id.keys())[p_i] for p in predictions for p_i in p]
return tokenized_sent, pred_tags
def ner_inference(tokenized_sent, pred_tags, checkpoint, name_len=5) -> list:
"""
NERμ μ€ννκ³ , μ΄λ¦κ³Ό μκ° λ° κ³΅κ° μ 보λ₯Ό μΆμΆν©λλ€.
Args:
tokenized_sent: ν ν°νλ λ¬Έμ₯μ΄ μ μ₯λ 리μ€νΈ
pred_tags: κ° ν ν°μ λν μμΈ‘ νκ·Έκ° (NER κ²°κ³Ό)
checkpoint: μ μ₯ν΄λ λͺ¨λΈμ λΆλ¬μ΄
name_len: λ μ νν μ΄λ¦ μΈμμ μν΄ μλ€λ‘ λͺ κ°μ μμ μ λ κ²ν ν μ§ μ§μ ν©λλ€.
Returns:
namelist: μΆμΆν μ΄λ¦(λ³μΉ ν¬ν¨) 리μ€νΈμ
λλ€. νμ²λ¦¬λ₯Ό ν΅ν΄
scene: μΆμΆν μ₯μ μκ° μ¬μ μ
λλ€.
"""
name_list = []
speaker = ''
tokenizer = checkpoint['tokenizer']
scene = {'μ₯μ': [], 'μκ°': []}
target = ''
c_tag = None
for i, tag in enumerate(pred_tags):
token = tokenizer.convert_ids_to_tokens(tokenized_sent['input_ids'][i]).replace('#', '')
if 'PER' in tag:
if 'B' in tag and speaker != '':
name_list.append(speaker)
speaker = ''
speaker += token
elif speaker != '' and tag != pred_tags[i-1]:
if speaker in name_list:
name_list.append(speaker)
else:
tmp = speaker
found_name = False
# print(f'{speaker}μ μλ¬Έμ΄ μ겨 νμΈν΄λ΄
λλ€.')
for j in range(name_len):
if i + j < len(tokenized_sent['input_ids']):
token = tokenizer.convert_ids_to_tokens(
tokenized_sent['input_ids'][i+j]).replace('#', '')
tmp += token
# print(f'{speaker} λ€λ‘ λμ¨ {j} λ²μ§Έ κΉμ§ νμΈνκ²°κ³Ό, {tmp} μ
λλ€')
if tmp in name_list:
name_list.append(tmp)
found_name = True
# print(f'λͺ
λ¨μ {tmp} κ° μ‘΄μ¬νμ¬, {speaker} λμ μΆκ°νμμ΅λλ€.')
break
if not found_name:
name_list.append(speaker)
# print(f'μ°Ύμ§ λͺ»νμ¬ {speaker} λ₯Ό μΆκ°νμμ΅λλ€.')
speaker = ''
elif tag != 'O':
if tag.startswith('B'):
if c_tag in ['TIM', 'DAT']:
scene['μκ°'].append(target)
elif c_tag =='LOC':
scene['μ₯μ'].append(target)
c_tag = tag[2:]
target = token
else:
target += token.replace('_', ' ')
return name_list, scene
def make_name_list(ner_inputs, checkpoint):
"""
λ¬Έμ₯λ€μ NER λλ €μ Name List λ§λ€κΈ°.
"""
name_list = []
times = []
places = []
for ner_input in ner_inputs:
tokenized_sent, pred_tags = get_ner_predictions(ner_input, checkpoint)
names, scene = ner_inference(tokenized_sent, pred_tags, checkpoint)
name_list.extend(names)
times.extend(scene['μκ°'])
places.extend(scene['μ₯μ'])
return name_list, times, places
def show_name_list(name_list):
"""
μ¬μ©μ μΉνμ μΌλ‘ λ€μ리μ€νΈλ₯Ό 보μ¬μ€λλ€.
Arg:
name_list: μΆμΆν μ΄λ¦ 리μ€νΈ
Return:
name: λμΌν μ΄λ¦μ΄ λͺ λ² λ±μ₯νλμ§ νμλ₯Ό ν¨κ» μ 곡ν©λλ€.
"""
name = dict(Counter(name_list))
return name
def compare_strings(str1, str2):
"""
nerλ‘ μΆμΆν μΈλͺ
μ νμ²λ¦¬νλ μ½λμ
λλ€.
λΉκ΅ν λ λ¬Έμμ΄μ κΈΈμ΄κ° λ€λ₯Ό κ²½μ°, λ 짧μ λ¬Έμμ΄μ΄ λ κΈ΄ λ¬Έμμ΄μ ν¬ν¨λλμ§ νμΈν©λλ€.
λΉκ΅ν λ λ¬Έμμ΄μ κΈΈμ΄κ° κ°μ κ²½μ°, κ²ΉμΉλ λΆλΆμ΄ 2κΈμ μ΄μμΌ κ²½μ° κ°μ μ΄λ¦μΌλ‘ μ§μ ν©λλ€.
μ΄ ν¨μμ μλμ combine_similar_namesλ₯Ό ν¨κ» μ€ννλ©΄, 'νλ€μ 'κ³Ό 'λ€μ μ΄', 'λ€μ μ΄κ°' λ±μ λͺ¨λ νλμ μΈλ¬Όλ‘ λ¬Άμ μ μμ΅λλ€.
Args: λΉκ΅νλ €λ λ λ¬Έμμ΄
Return: λ λ¬Έμμ΄μ΄ κ°μ μ΄λ¦μΌλ‘ νλ¨λ κ²½μ° True, μλ κ²½μ° False
"""
if len(str1) != len(str2):
# λ 짧μ λ¬Έμμ΄μ΄ λ κΈ΄ λ¬Έμμ΄μ ν¬ν¨λλμ§ νμΈ
shorter, longer = (str1, str2) if len(str1) < len(str2) else (str2, str1)
if shorter in longer:
return True
else:
same_part = []
for i in range(len(str1)):
if str1[i] in str2:
same_part += str1[i]
continue
else:
break
if len(same_part) >= 2:
return True
return False
def combine_similar_names(names_dict):
"""
compare_strings ν¨μλ₯Ό λ°νμΌλ‘ μ μ¬ν μ΄λ¦μ ν¨κ» λ¬Άμ΅λλ€.
2κΈμλ μ΄λ¦μΌ νλ₯ μ΄ λμΌλ κΈ°μ€μ μΌλ‘ μ§μ ν©λλ€.
"""
names = names_dict.keys()
similar_groups = [[name] for name in names if len(name) == 2]
idx = 0
# print(similar_groups, '\n',idx)
for name in names:
found = False
for group in similar_groups:
idx += 1
for item in group:
if compare_strings(name, item) and len(name)>1:
found = True
cleaned_text = re.sub(r'(μ|μ΄)$', '', item)
if len(name) == len(item):
same_part = ''
# μμ ν μΌμΉνλ λΆλΆμ΄ μλμ§ νμΈ
for i in range(len(name)):
if name[i] in item:
same_part += name[i]
if same_part not in group and cleaned_text not in group:
group.append(cleaned_text)
# print(similar_groups, '\n',idx, 'λ¬Έμμ΄μ κΈΈμ΄κ° κ°μ λ')
else:
group.append(name)
# print(similar_groups, '\n',idx, 'λ¬Έμμ΄μ κΈΈμ΄κ° λ€λ₯Ό λ')
break
if found:
break
if not found:
similar_groups.append([name])
updated_names = {tuple(name for name in group if len(name) > 1): counts for group, counts in (
(group, sum(names_dict[name] for name in group if name != '')) for group in similar_groups)
if len([name for name in group if len(name) > 1]) > 0}
return updated_names
def convert_name2codename(codename2name, text):
"""REλ₯Ό μ΄μ©νμ¬ μ΄λ¦μ μ½λλ€μμΌλ‘ λ³κ²½ν©λλ€. μ΄λ κ° μ½λλ€μμ λ²νΈλ λΉλμ κΈ°μ€ λ΄λ¦Όμ°¨μν κ²°κ³Όμ
λλ€."""
import re
for n_list in codename2name.values():
n_list.sort(key=lambda x:(len(x), x), reverse=True)
for codename, n_list in codename2name.items():
for subname in n_list:
text = re.sub(subname, codename, text)
return text
def convert_codename2name(codename2name, text):
"""μ½λλ€μμ μ΄λ¦μΌλ‘ λ³κ²½ν΄μ€λλ€."""
outputs = []
for i in text:
try:
outputs.append(codename2name[i][0])
except:
outputs.append('μ μ μμ')
return outputs
|